Implementing an active class to an element based on the current URL using Jquery in Django

Is there a way to dynamically add an "active" class to an element based on the href?

This is what my template in Django looks like:

<div class="panel side-panel-1 category">
<h4 class="title1">Sections</h4>
<ul class="clear-list">
{% for section in sections %}
    <li>
        <a href="/advert/adverts.aspx&sec{{ section.id }}">{{ section.name }}  ({{ section.advert_set.count }})</a>
    </li>
{% endfor %}
</ul>

The URLs will be generated using section.id

For example:

  • mysite.com/advert/adverts.aspx&sec1

In some cases, it may look like this:

  • mysite.com/advert/adverts.aspx&sec1&cat10&page1

Answer №1

Perhaps you could consider using the following code snippet:

class="{{ section.id ? 'active' : '' }}"
. This will add the 'active' class if the section.id exists.

<div class="panel side-panel-1 category">
<h4 class="title1">Sections</h4>
<ul class="clear-list">
{% for section in sections %}
    <li class="{{ section.id ? 'active' : '' }}" >
        <a href="/advert/adverts.aspx&sec{{ section.id }}">{{ section.name }}  ({{ section.advert_set.count }})</a>
   </li>
{% endfor %}
</ul>

Answer №2

Within the views.py file:

def display_adverts_by_section(request, advert_sec):
args = {}
args.update(csrf(request))
args['adverts'] =  Advert.objects.filter(advert_section_id=advert_sec).order_by('-advert_date', '-id')
args['sections'] = AdvertSection.objects.all().order_by('-name')
args['categs'] = AdvertCategory.objects.all().order_by('-name')
args['current_section'] = AdvertSection.objects.get(id=advert_sec)
args['username'] = auth.get_user(request).username
args['reg_form'] = MyRegistrationForm()
return render_to_response('adverts_sec.html', args)

Then, in the template:

{% for section in sections %}
    <li class="{% if section.id == current_section.id %}
                    active
                {% else %}
                {% endif %}">
        <a href="/advert/adverts.aspx&sec{{ section.id }}">{{ section.name }}  ({{ section.advert_set.count }})</a>
    </li>
{% endfor %}

If we have a "current_section", Django will compare it to the {{ section.id }} and the matching one will be assigned the 'active' class.

A big thanks to everyone who contributed!

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

An unforeseen repetition of jQuery Ajax calls

I'm currently working on an application that utilizes ajax calls to load content. However, I've encountered a situation where an ajax call goes into a loop but seems to end randomly. Below is the code sequence starting from a double click event l ...

The slider spills over the edges of the page

Seeking assistance – I managed to insert this logo slider onto my page. It seems to be functioning properly, but due to the width settings of the website engine, the modules are not fully stretching across the page. In an attempt to make the slider cove ...

interactive textbox created with the combination of javascript and php

Hello, I am new to JavaScript and jQuery. I am trying to create a dynamic text box using JavaScript that can add and remove rows. When I press the add button, it works well, but when I pressed delete, it deleted the entire table. Below is my JavaScript fu ...

Navigate through the contents of a table featuring intricate colspan and rowspan elements, while keeping both headers and left columns in

I am facing a challenge with a dynamically generated table that has complex structure including colspans and rowspans. My goal is to fix the headers and, if possible, even lock the first few rows on the left side while allowing the content of the table to ...

Creating a live data stream to listen for new additions to the database in PHP/CodeIgniter

I have implemented a code using ajax to fetch data from a MySQL database in real-time. Currently, the ajax call retrieves all the data and then loops through each entry to display it. What I am looking for is a way to avoid fetching all the data again and ...

Creating a responsive DataTable filled from a $.ajax request is a straightforward process that can greatly

I am in the process of creating an application that retrieves a lot of data from a web-service query and populates a data table with it. The data shows up correctly and styled properly on desktop, but when I switch to viewing it on a mobile device, the dat ...

Utilizing SVG within Sproutcore allows for seamless access to DOM nodes and the ability to effortlessly bind Sproutcore events directly to the DOM

Exploring Sproutcore, I am delving into the world of SVG (Standard Vector Graphics) integration within the app. The goal is to utilize a canvas for drawing elements like lines, boxes, and images, all of which SVG offers. My approach involved incorporating ...

What is the best way to create a view that caters to both administrators and regular users?

Currently, I am developing a system in Django which displays different fields and options based on whether the user is an administrator or a Jefe from the table. The administrator can access the panel in Django. class UsuarioCrear(SuccessMessageMixin, Crea ...

Guide to setting up django LOGGING with azure-log-analytics

I'm currently working on a Django app and I'm looking to implement logging to Azure Log Analytics. Previously, I was using Application Insights which was functioning well with my code. However, due to Azure's recommendation that it was outd ...

What could be causing the misalignment of these two divs?

I'm struggling to horizontally align these two divs using percentages for width. Even with padding and margin set to 0, they refuse to line up properly (the second one ends up below the first). This is the code I have been using: <div style="widt ...

To prevent the loss of form data, consider utilizing the input type button instead of the button element

I'm a bit hesitant to repost my question, but it appears that my initial query (Why won't my jquery display correctly) may have slipped through the cracks. My apologies for the lengthy block of code, but I'll include it all in hopes of provi ...

Poor Django and uwsgi performance

Running my django app with nginx & uwsgi involves the following uwsgi command: sudo uwsgi -b 25000 --chdir=/www/python/apps/pyapp --module=wsgi:application --env DJANGO_SETTINGS_MODULE=settings --socket=/tmp/pyapp.socket --cheaper=8 --processes=16 -- ...

When utilizing jQuery and Ajax for form submission, PHP is unable to retrieve any data

I'm encountering an issue when trying to submit a form with only a radiobutton group named radiob. The script I am using for submitting the data is as follows: <script type="text/javascript"> $(function() { $("#myForm").submit(funct ...

Error in the code that I am unable to locate in JavaScript, HTML, and CSS

I need help creating a navbar that displays the active site using HTML and JS code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content=& ...

Mastering the art of customizing jQuery Mobile skins

Just landed a front end developer role at a prominent bank where I'll be focusing on the UI using jQuery Mobile. I'm looking for a comprehensive page that contains all the assets of jQuery Mobile to streamline the skinning process. Any leads? ...

Django 1.8 fails to load static files

Hey there! I'm currently diving into Django with Onemonth Python and encountered an issue with loading static files. The HTML output seems to be correctly pointing to the file location, but I'm still facing some challenges. I am using Django 1.82 ...

What is the best way to shut down a browser using C#?

After clicking the Login button, I want to automatically close the browser if the login is successful. protected void btnLogin_Click(object sender, AuthenticateEventArgs e) { if (isAuthenticated) { // close the browser } } Since I am not using AJAX, thi ...

ajax.php form connected to a database using php

Introduction: I am currently working on a server-side datatables library. The code snippet below is not displaying either $stmt or $row, making it difficult to identify the issue. It's frustrating because I was hoping to troubleshoot this without see ...

"Enhance User Experience: Use CSS to highlight text selection based on

As a beginner in the world of css and html, I am eager to create a webpage that showcases a list of names with the ability to select one or multiple names. Instead of simply checking a box on the side, I would love for the background of the selected text t ...

Refreshing the view following a model update within an AJAX call in the Backbone framework

I'm struggling with my code as I can't seem to get my view to update after a model change. var ResultLoanView = Backbone.View.extend({ id:"result", initialize: function(){ this.render(); this.on('submissionMa ...