user1973967
user1973967

Reputation: 25

Add class on active menu link

I need to change the appearance of a link from a menu if it belongs to the current URL. I don't know how I can detect current URL and change a element class.

I would use jQuery

Upvotes: 0

Views: 212

Answers (3)

Jai
Jai

Reputation: 74738

What you can do is

  1. Get the location of the url
  2. use the .indexOf('.html') (Or your extension)
  3. Then use the .substr(url.lastIndexOf('/')) (this will give you the page name)
  4. Then use it with the class selector or id selector
  5. and fire the active class to that link on page load

How this will go see below:

lets suppose this is your url : http://localhost/myWebsite/index.html

 $(function(){ // this is done on doc ready function

    var url = window.location;
    var dUrl = url.substr(0, url.indexOf('.html'));
    var link = dUrl.substr(dUrl.lastIndexOf('/')+1);

    $('#'+link).addClass('active'); // on page load this will add the class to the corresponding link

 });

you can try this demo: http://jsfiddle.net/K9YAz/

Upvotes: 2

Christofer Eliasson
Christofer Eliasson

Reputation: 33875

You could use the properties of window.location to get the URL, or the parts of the URL that you need, of the current page. You could then select every anchor of the menu, loop over them, compare the value of their respective href-attributes with the URL of the current page. If they are equal, you add the proper class to the element.

Upvotes: 1

mjimcua
mjimcua

Reputation: 2799

$( document).ready(function (){
  $( function(){
    var url = window.location.pathname,
    urlRegExp = new RegExp(url.replace( /\/$/,'' ) + "$" );
    $('a').each( function(){
    if(urlRegExp.test(this .href.replace(/\/$/, ''))){
      $( this).addClass('active' );
    }
   });   
  });
});

Upvotes: 2

Related Questions