Highlight the active menu item using jQuery

Check out my menu example here: http://jsfiddle.net/hu5x3hL1/3/

Here is the HTML code:

<ul id="menu" class="sidebar">
<li> <a href="#" class="clickme">Menu</a>
    <ul id="menu1">
        <li><a class="dropdown-class-name" href="#">Dropdown link1</a></li>
        <li><a class="dropdown-class-name" href="#">Dropdown link2</a></li>
    </ul>
</li>

jQuery code:

    $('#menu1 li a').click(function(e) {
    $('a').removeClass('dropdown-class-name active');
    $(this).addClass('dropdown-class-name active');
});

CSS styling:

#menu1 li a.active{
    font-weight:bold;
}

Currently, when a dropdown link is clicked and a new page opens on the website, the active menu item loses its bold highlighting. How can I keep it bold on the new page?

I've attempted the following solution:

            $("#menu1 li a").click(function () {
          var url = window.location.href;
            if (url == (this.href)) {
                $('a').removeClass('dropdown-class-name active');
                $(this).addClass('dropdown-class-name active');
            }
        });

Unfortunately, this.href returns undefined and using a specific link instead also does not work as expected.

Answer №1

In order to properly execute the check, it is recommended to perform it within the dom ready handler rather than the click handler.

$('#menu1 li a').click(function (e) {
    $('a').removeClass('dropdown-class-name active');
    $(this).addClass('dropdown-class-name active');
});

var url = window.location.pathname;//it is important to confirm that this is the href value
$('#menu1 li a[href="'+url+'"]').addClass('dropdown-class-name active');

Answer №2

Give this a shot

$('#menu1 li a').click(function(e) {
    if($('a').hasClass('dropdown-class-name active')=="false"){$('a').removeClass('dropdown-class-name active');}
    $(this).addClass('dropdown-class-name active');
});

http://jsfiddle.net/abc123/7/

Answer №3

Check out the code below for it to function correctly

$("#menu1 li a").click(function() {
    var $linkElement = $(this); // storing it for multiple use
    // also, url == a.href will not be true if you have a relative URL in the link.
    // the URL will most likely be http://domain.com/pagename, and the href will just be the page name
    // if it is active, do nothing
    if (!$linkElement.hasClass("active")) {
        $linkElement.closest("ul").find("a.active").removeClass('active'); // remove active class
        $linkElement.addClass('active');
    }
});

Answer №4

Have you attempted to include the anchor reference in the selector?

var currentURL = '[href="'+window.location.href+'"]'

$('#menu1 li a'+currentURL).click(function(event) {
    $('a').removeClass('dropdown-class-name active');
    $(this).addClass('dropdown-class-name active');
});

Visit this link for further reference.

Remember, this script will only execute on click events, consider implementing it on page load as well.

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

Add the value to the array in MongoDb only if it does not already exist in

Looking to make updates to a nested array within a document only if the item is not already included in the array: await userCollection.findOneAndUpdate( { _id: ObjectId('616acc597ebda90ca6ffee21') }, { 'devices': { ...

The Jquery calculation feature sometimes mistakenly adds an incorrect value before calculating the correct value

Working on a calculator that accurately computes the field price and displays it, but facing an issue where the correct answer seems to merge with another value (likely from data-price as they match). Snippet of the code: var updateTotal = function() { ...

Position the Bootstrap Button on the right side of the navbar

Hey there, I'm completely new to the world of HTML/CSS and this is my first project ever. I welcome any constructive criticism that can help me improve in the future. Now onto my current dilemma: I've decided to use Bootstrap because it seems u ...

How can I retrieve the current background color and revert it back after a .hover event?

I am trying to use the .hover function to change the background color of a menu. Each menu item has a different background color, so I want it to return to its original color when the user hovers off. In other words, I want the script to read the current b ...

Implementing ExpressJS with MongoDB on a MERN Development Stack

After configuring my ExpressJS & MongoDB client and running Nodemon, I consistently encounter the following warning: "DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the ...

Are JavaScript Object notation and proper JSON the same thing?

When I execute valid JSON in the Chrome console: {"aaa":"bbb"} I encounter this error: SyntaxError: Unexpected token : But if I try something like this instead: {aaa:"bbb"} No error is thrown. Additionally, when running the following code ...

Issue with Three.js failing to display textures

I'm a beginner with three.js and I'm struggling to get my texture to render properly in my scene. Despite following the documentation closely, all I see is a blank canvas with no errors in the console. Can anyone offer any guidance on why my code ...

The event listener function is not functioning properly on images generated by JavaScript

I'm currently working on placing multiple images on a grid in the center of the page and would like to include a function that triggers when each individual image is clicked. The images are dynamically created using JavaScript and inserted into the do ...

Basic angular service malfunctioning

I've been trying to create an angular service but seem to be having trouble with it. I've attempted various solutions and searched extensively for answers. Any assistance would be greatly appreciated. //service angular .module('RDash ...

Having trouble with mysql_real_escape_string when using jquery load function

I recently encountered a strange issue where adding mysql_real_escape_string caused the page to not load. Here is the code snippet that seems to be causing the problem: $('.abandalink').click(function(){ var codigo_membro = $(this).attr(&a ...

The controls for the Bootstrap carousel component do not have a clear appearance

Trying to implement a Bootstrap carousel component but facing an issue with the controls not appearing transparent like in the example provided in the Bootstrap documentation. Check out the code snippet: <div class="carousel slide" id="s ...

Establish the predefined date for the air-datepicker

I am currently utilizing the air-datepicker inline feature. My objective is to establish the starting date for it. Below is the script detailing my attempt: export function load_datepickers_inline():void { const search_legs_0_datepicker = $("#search_leg ...

Having trouble with the contact form? It seems to be experiencing issues with

Hey there! I'm encountering an issue with the following codes, where I'm getting redirected and receiving an error message stating "Undefined variable: subject in C:\wamp\www\boot\send.php on line 42." Any help would be greatl ...

Filling a ButtonGroup in React with Buttons from an array

When trying to populate a ButtonGroup with Buttons using array.map(), I encounter an issue where the buttons do not appear. Interestingly, I used the same method successfully to populate a DropdownButton with MenuItems. Here is the functional DropdownButt ...

When jQuery is used to move rows between tables, it can interfere with

When moving rows between tables, everything seems to work fine. However, once the row is moved to the other table, all JavaScript functions related to that row stop working, and the reason remains unknown. The JavaScript code is simple - it involves takin ...

Why Changing the Width of a Flexbox Container Doesn't Impact Its Children?

Attempting to use TweenLite to animate the width of the blue sidebar down to zero, however facing an issue where the content breaks outside the parent's bounds. https://i.stack.imgur.com/4rEVr.png It is unusual for this to happen with Flexbox, given ...

Encountering an Unexpected Error in Next.js When Revalidating Paths

I'm facing an issue with my Next app where, despite editing a resource through an API endpoint following the pages-based system, the changes aren't reflected when I try to view or re-edit the resource. After checking the documentation, I discover ...

Using AJAX to submit multiple forms simultaneously

I have a challenge with my webpage that includes multiple forms. I want to implement a single submission button that will save all the forms simultaneously, as outlined below: <form id="form1" name="form1" action="someAction" method="post"> .... ...

Rendering Error - Animating text using React and Material-UI

Looking for a way to create a scrolling effect line by line? I have a component with name, pronouns, and some humble sub-text that should scroll one item at a time. To handle the scrolling feature, I've set up a separate component called TitleScroll. ...

What strategies can be used to effectively combine Server-side postbacks with jquery's animations?

My ultimate goal is to create something that surprises me every time: I am in the process of developing an application in the same way I always have: using some <asp:LinkButtons> (or regular buttons), displaying content in Panels with <asp:Updat ...