Highlight Active Menu Item With jQuery Script

We are able to improve the person revel in highlighting the energetic menu item on our websites. This makes navigation less difficult due to the fact the vacationer will recognize at the first look that is the current page.

This approach additionally will increase the number of visited pages because the traveler will more likely click the subsequent page when it’s less complicated to locate that.

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 with CSS.

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) {

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() {
    if ((window.location.pathname.indexOf($(this).attr('href'))) > -1) {

The second one example is parsing the hyperlinks best inside the .sidebar box and doesn’t upload the magnificence to the hyperlink but to its determine instead which is usually a li tag. The commented console.log line can help us to debug our code, to check which hyperlinks are parsed at the web 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, color adjustments will help to make it stand out.

Please follow and like us:

Leave a Comment

Your email address will not be published. Required fields are marked *