Using JavaScript to dynamically alter element class in Django templates

Within my django template, there is a list of Event items displayed using a for loop. Each event includes a date_of_occurrence attribute that holds a python DateTime value. My goal is to highlight events with a red background if the date is in the past relative to the current datetime.

This is what I initially envisioned:

In the template

<ul>
    {% for  event in events %}
        <div id="event_div"
            <li>
                event.name<br>
                event.date_of_occurrence
            </li>
        </div>
    {% endfor %}
    </ul>
    

In the CSS

.pastevent{
        background-color:red;
    }
    

I am seeking a JavaScript function that will assign the class 'pastevent' to the element with the id event_div. How can this function be implemented?

My understanding is that the function should not be triggered by a click event but rather when the page loads. How can the datetime value of each event passed from the template be used for comparison with the current JavaScript date?

Answer №1

Using javascript is not the only way to achieve this task. There are multiple options available using template tags.

A simpler (yet more basic) method would be to pass the current datetime to the template as a variable like "current_date" and then use logic checks within the template itself.

{% for event in events %}
    {% if event.date_of_occurrence < current_date %}  
    <div id="pastevent">
    {% else %}
    <div id="event_div">
    {% endif %}
    <li>
       event.name<br>
       event.date_of_occurrence
    </li>
  </div>
{% endfor %}

Another option could be to create a custom template filter that determines whether the event occurred in the past or not, and implement similar logic as mentioned above.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Fabric.js Textbox does not automatically wrap long text in version 5.3.0

I am currently using fabric.js version 5.3.0. The Textbox object in fabric.js will wrap text when you add space between words, but it won't wrap when you add text without any spaces. Please take a look at the following fiddle: https://jsfiddle.net/N ...

How can I customize the color of Bootstrap spinners without using text color utilities?

After incorporating a Bootstrap-4 spinner (outlined in this guide) on my webpage, I noticed that only the standard text color utility colors can be applied to it (such as primary, warning, success...), which feels restrictive. I want the flexibility to m ...

Experiencing issues with obtaining the correct data format in JSON when making an AJAX request

After writing a GET API, I am trying to display some records in a data table. However, when retrieving the records in JSON format, the date values are coming in this format: "/Date(1498849454000)/". How can I convert this into "2017-04-11 02:09" format? Th ...

Pass a variety of data points to PHP using Ajax requests

I am facing a challenge with passing multiple parameters during Ajax calls. The code works perfectly when I only pass one parameter. Here is the code snippet for the Ajax call: $.ajax({ type: "POST", url: "dataCartas.php", ...

Choosing checkboxes, radio buttons, and lists

Having difficulty with dynamically checking/selecting radiobuttons, checkboxes, and list styles using jQuery/jQuery Mobile. I have a collection of checkboxes, radio buttons, and select menus. My goal is to fetch the value from the database and automatical ...

Can you guide me in utilizing this API endpoint efficiently to enable search functionality using React Query?

const { isLoading, isError, data, error, refetch } = useQuery( "college", async () => { const { result } = await axios( "http://colleges.hipolabs.com/search?name=middle" ); console.log(&quo ...

Encountering an error when importing chart.js-plugins-annotations

import { annotation, Chart, defaults } from 'chart.js'; An issue arises when using this import statement: localhost/:1 Uncaught TypeError: Failed to resolve module specifier "chart.js". Relative references must start with either &quo ...

Using Regex named groups in JavaScript's replace() method

Currently in my JS project, I am facing a challenge while trying to create an object using the code snippet below. My difficulty lies in extracting regex named groups using the replace function provided. var formatters = { 'p': 'padding& ...

What is the best way to retrieve the focused element in a shiny application?

I'm trying to figure out if there's a way to determine in shiny whether the user is focused on a text-field or select field. My website contains various elements such as plots, tables, numerical inputs, and buttons. Currently, I have implemented ...

Pause/advance video by clicking manually

How can I create a functionality where a video ends when a user clicks on a skip button to allow them to skip the video? I have successfully used the following code, which triggers an action when the video reaches its end. HTML <video autoplay> ...

Guide on effortlessly cropping images that exceed screen height in React Bootstrap

Currently, I am working on developing my personal website with a vision of featuring a captivating picture slideshow using a Carousel tool. My goal is to place this slideshow in the rightmost 10 columns of the screen where the images will occupy the full w ...

The attempted creation of the ui.tree module failed with the error: [$injector:nomod] Unable to find module 'moduleName'! This could be due to a misspelling of the module name or

In my AngularJS project, I am utilizing a third-party library called angular-ui-tree to display data. To integrate this library, I need to include ui.tree as a dependency in my main app module. Following the instructions provided in the link, I have succes ...

Background of jQuery-UI Slider

Can the background color of a jQuery-UI Slider widget be set using JavaScript? This is the default setting: What I am trying to accomplish is the following: The green range should be determined based on historical data. I want to visually show the user ...

The local npm package that has been installed is not linked by symlink

After running the command npm i ./my_modules/mypackage, I noticed that the local npm package was added to my dependencies as: "dependencies": { "mypackage": "file:my_modules/mypackage" } Although it appeared in the no ...

The right floated div gracefully hovers in the center of the page as the page finishes rendering

The website features a dynamic layout, with a log in status section that is aligned to the top right corner of the page. However, there seems to be an issue where this element remains centered on the page until all content is fully loaded, at which point ...

Locate the next element with the same class using jQuery across the entire document

I'm working with the following HTML: <section class="slide current"></section> <section> <div class="slide"></div> <div class="slide"></div> </section> <section class="slide"></section> ...

Ensuring Proper Alignment in Bootstrap

https://i.sstatic.net/bGTXG.jpg https://i.sstatic.net/4Vh1k.jpg Having some difficulties displaying JSON data in a grid layout with React. Facing the following challenges: Uneven spacing due to less margin on the left side. Attempts to align ...

How can I convert a DateTime from UTC to my local time zone?

Currently, I am facing a challenge while working with MongoDB as I attempt to deserialize a BsonDate into a DateTime object with the correct Kind. The issue arises when the serialized DateTime is stored in UTC format in MongoDB and deserialized back in UTC ...

Display a loading component within the navbar in React while waiting for data to be retrieved

I recently updated my navbar component to accept dynamic values for menu titles. One of these dynamic values is the username, which needs to be fetched asynchronously. To handle this, I decided to display a loading animation until the username is fully fet ...

Tips for sorting through a deeply nested array of objects based on specific values and retrieving the parent object

I am facing an issue with filtering a JSON object that contains nested arrays and objects. Here is an example of the structure: [ { name: 'data 1', users: [ { username: 'user 1', full_name: 'name 1&a ...