Use jQuery To Highlight Active Menu Item

If you are using menus on your web designs it's a common web design technique to highlight the current page that you are on to show you where you are on the site.

This technique is normally done by adding a CSS class to the menu item to highlight it differently to the other menu items.

If your using a WordPress site then you are most likely using the WordPress function wp_nav_menu() to display the menu items. In wordpress this function will automatically add a CSS class of current_page_item to the current page. But if your using a static website then you will need to add this CSS class on every page of your site, if there are a lot of pages on your site then this can take up a lot of time.

Here is a jQuery snippet which will check the current page URL and compare it with the URLs in the menu and if they match it will add a class to the menu item.

<script type="text/javascript">
        // Get current url
        // Select an a element that has the matching href and apply a class of 'active'. Also prepend a - to the content of the link
        var url = window.location.href;
        $('.menu a[href="'+url+'"]').addClass('current_page_item');

The above solution will only work for absolute URLs, which will not work on every website if they use relative URLs.

@micha149 has shown me this jQuery snippet which will catch all absolute and relative URLs.

var url = window.location.href;

// Will only work if string in href matches with location
$('.menu a[href="'+ url +'"]').addClass('active');

// Will also work for relative and absolute hrefs
$('.menu a').filter(function() {
    return this.href == url;
Back to top ^

Join Paulund

  • Get access to 100s of premium tutorials and downloadable content
  • Members content consists of Premium WordPress plugins, CSS packages, jQuery packages, tutorial demo files and templates for 100s of web development tutorials
  • In-depth development tutorials
  • Priority tutorial requests
  • Priority email development support
  • No ads

Here at Paulund you'll find Web Development tutorials and snippets focusing mainly on PHP, WordPress and CSS. Members will get access to premium tutorials that go into more detail about development with these languages. You will also get access to downloadable premium content based on the tutorial.

Join Paulund

Leave a Reply

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