The navbar elements fail to highlight when executed within my JavaScript script

I'm attempting to emphasize the navbar items for each page that the user is currently viewing, although my code logic seems correct, it's not functioning as expected. Below is the basic navbar that is consistent across all pages:

    <nav class="navbar-container">
        <ul class="navbar-top">
            <li><a class="nav-l" href="{{ url_for('home') }}">Home</a></li>
            <li><a class="nav-l" href="{{ url_for('gallery') }}">Gallery</a></li>
            <li><a class="nav-l" href="{{ url_for('prices_delivery') }}">Prices and Delivery</a></li>
            <li><a class="nav-l" href="{{ url_for('contacts') }}">Contacts</a></li>
        </ul>
    </nav>

Below is the CSS snippet that changes the color of the current link to red when a certain class is added to the <a> tag:

.navbar-top .current {
    color: red;
}

Finally, here is the JavaScript code related to this functionality:

function navbarHighlight() {
    let navLinks = document.querySelectorAll('.nav-l');

    navLinks.forEach(navLink => {
        navLink.addEventListener('click', function() {
                navLinks.forEach(navLink => navLink.classList.remove('current'));
                navLink.classList.add('current');
            });
        });
}

Answer №1

When you click, your page is refreshing itself. Adding a class on a 'click' event in JavaScript may result in the element having that class momentarily before the page changes and refreshes, seemingly ignoring your JavaScript code.

This type of functionality is better suited for server-side processing. If you do want to keep it client-side based on the 'click' function, I suggest utilizing 'sessionStorage' to track which navigation button was last clicked. This way, upon page refresh, you can retrieve the information from sessionStorage and highlight the current page accordingly. Another option is to utilize window.location to determine the current page and apply highlighting based on that.

Answer №2

(function highlightNavbar() {
    let links = document.querySelectorAll('.nav-l');

    links.forEach(link => {
        link.addEventListener('click', function() {
                links.forEach(link => link.classList.remove('active'));
                link.classList.add('active');
            });
        });
})()
.navbar-top .active {
    color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav class="navbar-container">
        <ul class="navbar-top">
            <li><a class="nav-l" href="#">Home</a></li>
            <li><a class="nav-l" href="#">Gallery</a></li>
            <li><a class="nav-l" href="#">Prices and Delivery</a></li>
            <li><a class="nav-l" href="#">Contacts</a></li>
        </ul>
    </nav>

Answer №3

Appreciate the help, I managed to make it function using an alternate approach:

let currentURL = window.location.href;
let menuItems = document.querySelectorAll('a');
let totalMenus = menuItems.length;

for (let j=0; j< totalMenus; j++) {
    if (menuItems[j].href === currentURL){
        menuItems[j].classList.add('active')
    }
};

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

Display content in two columns. If the width of the left column is too narrow, move the content in the right column

In my layout, there is a wrapper div with two child elements: left div and right div. The left div contains text which can be lengthy, while the right div holds an image loaded asynchronously without known width: <div id="wrapper"> <div id="l ...

Which is more efficient: storing a value in cache or invoking a function?

I'm torn between these two versions of code - Which one is better? var getKey = function(e) { return e.keyCode || e.which; }; function doSomething() { if(getKey(e) === 32 || getKey(e) === 9 ) { // do something } } OR function ...

What are some strategies for testing a dynamically loaded component in Vue?

Here is the code snippet of the component I am currently testing: <template> <component :is="content" /> </template> <script setup> import { defineAsyncComponent } from 'vue' import { useRoute } from 'vue ...

Creating a 404 Error Response in Express.js

Inside app.js, I currently have the following code: // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); This code executes when a non-existent URL ...

What is the best way to place an anchor tag with an image inside a bootstrap grid cell?

I am facing an issue with a 9-cell grid that contains images using Bootstrap columns. The grid is responsive and functions perfectly when only images are present. However, I want to make the images clickable by placing them inside anchor tags (<a>). ...

Understanding the Usage of FormData in NextJS

I'm trying to read fetch's body contents. Here's the code I'm using: fetch('/api/foo', { method: 'POST', body: new FormData(formRef.current), }); https://i.sstatic.net/6YB1V.png Now I need to parse the body dat ...

While using Tcpdf, I encounter an issue where the textarea value I pass is not being printed in the desired format

Currently, I am experimenting with TCPDF to create PDF files from HTML. However, I have encountered an issue where passing a variable containing text results in the text being printed on separate pages for each line. Is there a way to ensure that the tex ...

The Bootstrap datepicker functions properly when used in plain HTML, but encounters issues when implemented within the .html()

Using HTML: <input class="m-ctrl-medium date-picker" size="16" type="text" id='lateETD1' name="dateRecv" value=""/> Not working with script: var ETD = $("#ETD"); ETD.html("<input class='m-ctrl-medium date-picker' id='la ...

What is the best way to alter a key within a for loop in real time?

I am looking to dynamically change the key in a for loop. To better explain my needs, I have created a demo using the playground from this link. My requirement is to be able to switch keys based on certain logic, as the keys in the array data may vary dep ...

Exploring the integration of Polymer elements within a .Jade document

Recently, I began delving into the world of Polymer and web development. I noticed that the Polymer elements load perfectly when I view the HTML file in my browser. However, when I convert the HTML file to Jade format, the resulting Jade file does not disp ...

Retrieve the successful response data from an AJAX request

When I pull information from my MongoDB database, I receive a temporary value in the success part using $.ajax. How can I access this temp_value outside of the $.ajax function to ensure that tmp_result is set to 10? **javascript** var tmp_object = ...

Locate identical values in Vuejs

When working with an array of objects, I need to check if a newly inserted object is a duplicate or not. this.duplicate = false; for(let item of this.items){ if(item.id && this.item.name === item.name) { t ...

Drop-down menu with caret using HTML and CSS

Is there a way to include a dropdown caret for the account link in the html code provided below? . . . <nav> <ul id="menu"> <li class="home"><a href= "home.html" class="menu" >&l ...

The call stack size has been exceeded in Next.js, resulting in a RangeError

Currently attempting to deploy my project on vercel.com but encountering an error specifically with 3 pages that have no internal errors. An error occurred while prerendering the page "/applications". For more information, visit: https://nextjs.org/docs/me ...

Photo uploading in ASP.NET MVC - encountering null HttpPostedFileBase issue

QUESTION: I'm having an issue where the Photo1 value is null in the controller post method despite uploading it. Can someone help with this? This is my model class: class ProductVM{ public string Name { get; set;} public string Color {get; ...

What is the best way to iterate through the <tr> elements of a table based on the number of days in a particular month?

I am looking to showcase the year and month of a date in form2, looping the number of days corresponding to that month. Please review the source code for better understanding. <div id="form1"> <div class="form-group"> <label>Da ...

Incorporating Anchor Text as the Title in Real-Time

As of now, I have this snippet of HTML code <a href="http://www.google.com">Google Website</a><br /> <a href="http://www.yahoo.com">Yahoo Website</a><br /> <a href="http://www.bing.com">Bing Website</a& ...

Motion graphics following the completion of a form input

In my HTML, I've created a div container with a form field: <div class="flex_item" id="b_one"> <form id="f_one"> <input id="i_one" type="text"> </form> </div> I'm attempting to change the backgroun ...

Is it possible to generate a triangular attachment below a div element?

My designer sent me a unique design and I'm wondering if it's possible to replicate using HTML, CSS, or JavaScript? https://i.stack.imgur.com/spB71.png I believe it can be done with CSS by creating a separate div positioned absolutely under the ...

Is there a way to enable my progressBar to be draggable so that when clicked, it adjusts to a new currentTime position

I am trying to create a seekable audio progress bar in React, but I am facing issues with the seek function not working as intended. Below is my main play buttons file where all the code related to the progress bar is located. import React, { Component } ...