jQuery add ACTIVE class


/ Published in: JavaScript
Save to your folder(s)



Copy this code and paste it in your HTML
  1. var url = window.location.pathname,
  2. urlRegExp = new RegExp(url.replace(/\/$/,'') + "$"); // create regexp to match current url pathname and remove trailing slash if present as it could collide with the link in navigation in case trailing slash wasn't present there
  3. // now grab every link from the navigation
  4. jQuery('#nav li').each(function(){
  5. // and test its normalized href against the url pathname regexp
  6. if(urlRegExp.test(this.href.replace(/\/$/,''))){
  7. jQuery(this).addClass('active');
  8. }
  9. });
  10.  
  11. });

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.