What could be the reason for JQuery not updating the CSS class?

Seeking assistance with a jQuery issue. When clicking a link in the navbar, I am attempting to change its style (background and font color). Here is the code I am using:

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <script>
            $(document).ready(function(){
                $("ul li a").click(function(){
                    $(this).addClass("active");
                });
            });
        </script>

The CSS seems correct as hardcoding the class="active" into the HTML displays the desired style. However, upon clicking a link in the navbar, all the links flash in and out of the style instead of just the clicked link. The outcome resembles the CSS :active selector behavior, but all links flash simultaneously.

Below are the relevant HTML elements:

            <li><a href="/">Home</a></li>
            <li><a href="/repository">Repository</a></li>
            <li><a href="/events">Events</a></li>
            <li><a href="/bio">Bio</a></li>
            <li><a href="/contact">Contact</a></li>
        </ul> 

Appreciate any assistance or insights. Additionally, I am utilizing Flask and Bootstrap for this project. Any guidance would be valuable as this is my first website endeavor.

Answer №1

Give this a shot

$(document).ready(function(){
            $("li").find("a").on("click",function(){
                $(this).addClass("active");
            });
        });

Answer №2

The links you mentioned have a specific structure:

<ul class="navvy" id="responsive-navvy"><li><a href="/">Home</a></li>

You've expressed a desire to navigate through these links.

When you follow this type of link, a request is sent to the server. Upon receiving a response, the browser reflows the page's DOM (including any class modifications) with the new HTML content.

You have two options:

  • Avoid following the link.
  • Add the appropriate class dynamically to reflect the current page.

Regarding the first option: If you choose not to follow the link, no server request is made, and the page isn't updated. Instead, you can update the page using methods like replaceState or pushState to alter the URL without changing the page content, and then manipulate the DOM separately.

As for the second option: If you prefer following the link and having the server control the content, you can use the following code to highlight the relevant navigation link on page load:

$(function() {
    $("ul li a[href=" + location.pathname + "]").addClass("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

Managing scroll position based on media queries in JavaScript

I'm currently working on implementing a fade-in/out effect on scroll for a web project. In my JavaScript code, I need to specify a certain value for the scroll position, such as an offset, to trigger the effect. The issue: The offset value may not ...

Tips for creating a form that adapts to different devices, ensuring it looks great no matter the screen size

<div class="modal" id="myModal" style="width:50%; top:15%;" role="dialog" > <div class=""> <!-- Modal content--> <div class="modal-content"> ...

Send multiple values as arguments to a jQuery function

Beginner question ahead: I'm using the jquery function loadNewPicture() to upload pictures and the progress() function to track the percentage of the upload. Everything is functioning correctly. My query relates to the variables that can be passed t ...

Update the html() function to include any content that has been typed into a

I have a webpage structured like this: <div id="report_content"> Some information <textarea name="personal"></textarea> <b>Other information</b> <textarea name="work"></textarea> </div> Whe ...

Display all pages in the DataTables plugin while utilizing responsive tables and additional features

I am struggling to combine the responsive and fixed header attributes of my current function with the "Show All" list feature, similar to what is demonstrated in this example: https://datatables.net/examples/advanced_init/length_menu.html I need assistanc ...

Utilizing a JavaScript class method through the onchange attribute triggering

I am facing an issue with a simple class that I have created. I can instantiate it and call the init function without any problems, but I am unable to call another method from the onchange attribute. Below is the code for the class: var ScheduleViewer = ...

The transition in Vue Js is only effective when elements are entering, not when they are

Attempting to implement a vue js transition from bottom to top and top to bottom. The transition works smoothly from bottom to top when entering, but there is no transition effect when leaving. Below is the CSS code for the transition: .slide-details-mob ...

Applying Bootstrap's inline styling to adjust the width of a label

I'm having trouble adjusting the width of a Bootstrap label using inline styles. Here is my code: <td><span class="label label-info" style="width:30px; text-align:center; background-color:#6d8cbf"> TEXT </span></td> Unfort ...

Do jQuery and AJAX both support application/json content type in all web browsers?

I have been managing my ajax requests like this: @header("Content-Type: text/html; charset=".get_option('blog_charset')); and in the JavaScript: $.ajax(.... ... success: function(response){ var obj = eval('('+response+') ...

What is the best way to use jQuery to find and select an "a" tag that links to a file with a specific

My goal is to select links that have different types of files using jQuery: jQuery('a[href$=".pdf"], a[href$=".doc"], a[href$=".docx"], a[href$=".ppt"], a[href$=".pptx"], a[href$=".xls"], a[href$=".slxs"], a[href$=".epub"], a[href$=".odp"], a[href$=" ...

Grab the table headings from an HTML table and store them in variables after accessing the DOM

Looking to modify the structure of the DOM. Wanting to display table content using paragraphs instead. To achieve this, I need to extract data from each row in the table. How can I accomplish this task? <table style="width:300px"> <tr> ...

Tips for containing `overflow` within a flexbox container

I've organized my body space into three sections: header, content, and footer. To achieve a sticky footer effect at the bottom, I used the flex property in my layout. However, I'm struggling to add a scrollbar to my main container box. I've ...

SwiperJS continuously applies additional right margin to every slide

My Swiper carousel seems to be adding an unnecessary 5px margin-right to each slide, resulting in the cards not fitting into one frame. https://i.sstatic.net/fwn5G.png I attempted to fix this by setting the margin-right to 0px for the .swiper-slide class ...

Explore various date formats using the datepicker functionality

I'm dealing with the code below: <script type="text/javascript" language="javascript" src="~/Scripts/bootstrap-datepicker.min.js"></script> <script type="text/javascript" language="javascript" src="~/Scripts/locales/bootst ...

The modals equipped with data-dismiss="modal" and data-target="#id" do not navigate to their intended destination

Attempting to focus the input field using the modal data-target function on button click. The input field is focused, but a div called <div class="modal-backdrop in"> is created and the modal does not close properly. This prevents the user from click ...

Utilizing Laravel for Making Ajax Calls to Controller

I am a beginner in using Laravel and I am trying to create an API with Laravel using AJAX calls. However, when I make the AJAX call, the URL appears to show an invalid server path. Below is my code: My Route file : Route::get("a/b","AController@c"); My ...

Shopify's Ajax Cart experiences persistent loading issues when attempting to insert an <img> element within the code

I'm currently experiencing some difficulties when trying to insert a small image beneath the Check Out button on Shopify. I have attempted various locations without success, and I am using the Brooklyn theme. My approach involves using liquid tags an ...

Harness the power of Highcharts through an Ajax request to retrieve a JSON file

I am having an issue using Highcharts with a JSON file from an external server. When I try to bind the returning file to the chart in my ASP.NET MVC application, it doesn't work. Here is the code I have attempted: http://jsfiddle.net/Q6ngj/2/ jQuery ...

Attempting to imitate the hover effect of a scroll-down button

Looking for advice on creating a scroll down button with a hovering effect similar to the one found on this website - . Any tips or suggestions would be greatly appreciated. ...

"Upon loading the page, Placeholder automatically triggers the opening of the jQuery UI autocomplete combobox in IE10

While utilizing the jQuery UI autocomplete combobox widget, I encountered an issue where adding placeholders to my comboboxes caused the autocomplete boxes to be opened by default. This specific problem is visible only in IE10 and later versions. Below i ...