Add class to links if they match the browser URL (menu active state)

Dec 1, 2014 3:59 pm

Hey Everyone,

Here is a javaScript function that when placed in the <head> of your websites, it will read the browser's url and compare it with links on the page. If they match, it will add a class of "active" to the link.

This allows you to target links that are showing the current page.

Notice below that the script is targeting all links within the id "menu". Change this to the id that your menu(s) are located in.

<script type="text/javascript”>
     $(document).ready(function(){
          $('#menu a').each(function(){
               // and test its normalized href against the url pathname regexp
               if(window.location.href == this.href){
                    $(this).addClass('active');
               }
          });
     });
</script>