Highlight Active Menu Item With jQuery Script

We can improve the user experience highlighting the active menu item on our websites. This makes navigation easier because the visitor will know at the first glance which is the current page.

highlighted active menu link script


This strategy also increases the amount of visited pages because the visitor will more likely click the next page when it’s easier to navigate on the site.

In this article I’m going to present a lightweight jQuery script that will parse the links on the page and assign a class to the ones that point to the URL of the current document. We will have to style the highlighted link class editing the CSS.

current sidebar item color

Our example works great for highlighting sidebar menu items as well. Screenshot from Ruwix.

The Script To Highlight The Menu Item

We can place the script inside the document.ready function to be executed when the page has finished loading: $(document).ready(function(){ … });

$("a").each(function() {
    if ((window.location.pathname.indexOf($(this).attr('href'))) > -1) {
        $(this).addClass('activeMenuItem');
    }
});

The program parses each anchor tag on the page and if the current page link contains the href attribute of the link then adds the activeMenuItem class to it.

We can further enhance our code:

$(".sidebar a").each(function() {
    //console.log($(this).attr('href'));
    if ((window.location.pathname.indexOf($(this).attr('href'))) > -1) {
        $(this).parent().addClass('activeMenuItem');
    }
});

The second example is parsing the links only inside the .sidebar container and doesn’t add the class to the link but to its parent instead which is usually a li tag. The commented console.log line can help us to debug our code, to check which links are parsed on the page.

The CSS Code

a.activeMenuItem {
    background-color: #F00;
    font-weight: bold;
}

You will obviously amend this example, I just want to draw the attention that the styling is necessary to make the highlighted link stand out. Usually a color adjustments will help to make it stand out.