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">
    jQuery(document).ready(function($){
        // 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');
    });
</script>

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;
}).addClass('better-active');

UpChecker

Reliable uptime monitoring and instant alerts for any website downtime.

  • Uptime Monitoring
  • Performance Monitoring
  • SSL Certificate Alerts
  • Domain Monitoring
  • DNS Checker
  • XML Sitemap Monitoring