Transforming navigation bar icons to active using Django and JavaScript

I recently created a navbar using Bootstrap 4 and I'm looking for a more efficient way to toggle the active icon on the current page. Here's my current setup:

<li class="nav-item"><a href="/" id="A"
                      {% if request.path == "/" %}
                        class="nav-link active" 
                      {% else %}
                        class="nav-link"
                      {% endif %}>Home</a></li>
<li class="nav-item"><a href="/blog" id="B"
                     {% if request.path == "/blog/" %}
                     class="nav-link active" {% else %}
                     class="nav-link"
                     {% endif %}>Blog</a></li> 

Instead of this lengthy code, I would like a simpler solution that can activate a script based on URL names. Here's what I have in mind:

{% if request.path == '/' %}
<script>
document.getElementById("#A").classList.add('active');
if ( document.getElementById("#A").classList.contains('active') )
document.getElementById("#A").classList.toggle('active');
</script>

{% elif request.path == '/blog/' %}
<script>
document.getElementById("#B").classList.add('active');
if ( document.getElementById("#B").classList.contains('active') )
document.getElementById("#B").classList.toggle('active');
</script>
{% endif %}

Is there a better and easier approach to achieve this? I welcome any suggestions on how to highlight the active page icon on the navbar with toggling styles. Thank you.

Answer №1

To adhere to the DRY principles and avoid hard-coding URLs, consider using the reverse function in your templates.

For example:

<!-- At the beginning of the page -->
{% url 'index' as index %}
{% url 'blog' as blog %}

<!-- ..... Page content goes here ..... -->

<li class="nav-item">
    <a href="{{ index }}" id="A" class="nav-link {% if request.path == index %}active{% endif %}">
        Home
    </a>
</li>
<li class="nav-item">
    <a href="{{ blog }}" id="B" class="nav-link {% if request.path == blog %}active{% endif %}">
        Blog
    </a>
</li> 

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

Generate dynamic arrays in JavaScript/jQuery

I am encountering a challenge in creating a specific array for a project. The array needs to have the following fields consistently: [id | Type | nbItems] Following that, we have: m_name : m_value : However, the number of m_name/m_value pairs can v ...

Unusual occurrences observed with table cell padding in CSS

When I include a TD padding in my CSS like this: #maincontent table td, #maincontent table th { padding: .333em 0 .333em .25em; } In Safari and IE, the padding is applied correctly to the TD, but not in Firefox. If I apply the TD padding only to th ...

Swap out the div block with a new one

I am currently facing an issue with my JavaScript code. The code is supposed to remove block1 and replace it with block2 when an onclick function is triggered. function buyerclick() { div = document.getElementById('block2'); div.style.displa ...

Issue with video.js text track memory leakage (WebVTT/VTT)

I am utilizing Video Text Tracks to showcase advanced live information on top of the video. A new video is loaded every few minutes, each with its own .webvtt file (consisting of 2-3k lines). Although everything is functioning properly, there is a persis ...

Exporting JSON data to an Excel file using an array of objects with embedded arrays

I am currently developing a fitness application that allows users to create workout routines and download them as an excel file. The data is structured as an array of objects, with each object representing a workout date and containing details of the exerc ...

Evaluation of django API view pagination

As a newcomer to Python Django and currently utilizing APIView, I am delving into pagination code. Upon reviewing numerous code snippets, one common concern arises. The standard approach involves fetching all the data from the database table and then appl ...

Creating a versatile table design using flexbox

Looking to create a gallery for images and videos using flexbox properties to create a dynamic table of divs to hold media. The challenge is generating the table automatically without specifying the number of rows and columns needed. For example, if I ha ...

What is the best way to integrate a VueJS application into an already established web page?

Working on a project involves fixing issues with legacy components in a server-rendered web page. I proposed rewriting these parts in Vue to facilitate our migration, and the team approved. I created a mini-app using the Webpack template from Vue CLI, whi ...

Launch a web application utilizing a node.js server hosted on Firebase

I am currently developing a web application using Vue. In this app, I have integrated "pusher" for real-time multi-user communication. I have set up a node.js server on port 5000 of a specific device within my local network. The app functions smoothly with ...

Unable to physically tap on the checkbox input, though able to perceive the value it holds

When running my protractor test, I encountered an issue with the following statement: await element(by.model('publishCtrl.isPublishedInAllRegions')).click(); The test failed and returned an error message stating "ElementNotVisibleError: element ...

Assign a specific material to a specific portion of a mesh in Three.js

In the world of three.js, imagine having a 3DObject that looks something like this: const geometry = new THREE.BoxGeometry(1, 1, 1); const material = new THREE.MeshStandardMaterial({ color: 0xff0000 }); const mesh = new THREE.Mesh(geometry, material); ...

Is your Bootstrap accordion expanding correctly, but having trouble collapsing?

I'm encountering an issue with a bootstrap 5 accordion. The panels expand correctly, but they do not collapse back down. I'm unsure if there's a problem with my JS or CSS. No errors are showing up in Chrome's console. When I transferre ...

How can a JavaScript function communicate with a code behind method?

Currently, I am trying to implement a JavaScript function for an HTML img click event on an aspx page. Additionally, there is a server method in the code behind page that I need to call from the JavaScript function without any parameters whenever the user ...

Is it possible to embed a Blazor component as a Web Component in a standard HTML page that is not using Blazor?

Is there a way to render a Blazor component as a standalone DOM fragment, or integrate it as a standard Web Component in a vanilla HTML/JS page? This question may seem simplistic from the perspective of Blazor architecture. While I'm no expert in Bla ...

Determining the precise margin within a nested div structure

Hopefully, my description of a "nested div" was accurate. My current situation involves an image within a div structured like this: content -> content-inner -> column_left I'm struggling to start the image at 0 px (the extreme left side of th ...

Javascript is unable to access the occupied value. Error: Unable to read property 'weight' of undefined

I encountered a strange issue that I wasn't expecting. The snippet of code below represents a simple function. However, the problem arises when I try to access 'truckArray[0].weight' and receive an error stating TypeError: Cannot read prop ...

Cannot access pseudo elements in the Microsoft Edge browser

Is there a workaround for not being able to select or access the properties of :before & :after elements on Microsoft Edge's inspect element? .arrow_box { position: relative; background: #d43959; border: 4px solid #ac1f3c; width ...

passing JSON data using JavaScript or jQuery

I have a JSON snippet that I need to parse using JavaScript or jQuery and convert into variables: name and meetup. Can you help me with this? Below is the JSON code: { "MYID": 1, "module": [ { "name": "Manchester", ...

How to send data to Material-UI drawer components

In the component called Setup, there are input fields that each hold their own data stored in an object named dropdowns. Alongside each input field, there is a drawer component containing the ID of that specific input field. I have a function called handle ...

PostGIS provides full support for geographic objects allowing you to store and query spatial data with Geo

My plan involves using Django (2.0.6) with Postgres/PostGIS as a backend (10/2.4?), but I want to store model geometries as 100% pure 3D Cartesian coordinates, regardless of the SRID reference. How should I declare model fields to ensure they maintain pur ...