3

I have the following code that should add an active css class to the menu item if menu item url == current url:

$("#accordion a").each(function() 
{   
    if (this.href.search(window.location.hostname) != -1)
    {
        $(this).addClass("active-sidebar-link");
    }
});

but this adds the class to all the menu items. any tips?

1
  • window.location.hostname would return you the page hostname i.e. stackoverflow.com. You should instead use location.href or location.pathname to get the correct match. Commented May 15, 2012 at 4:51

4 Answers 4

12

Try this:

$("#accordion a").each(function() {   
    if (this.href == window.location.href) {
        $(this).addClass("active-sidebar-link");
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

This works, however it will break if the URL has a fragment. For example domain.com/folder/#top.
Using pathname instead of href should help.
3
$('#accordion a[href="'+ window.location.hostname +'"]').addClass('active-sidebar-link');

Comments

0

If you want to do this with jQuery, you can:

$("#accordion a").addClass(function(){
  return this.href === window.location 
    ? "active-sidebar-link" 
    : "" ;
});

However, there's a far better way to style current-page links. This generally involves given the body element a classname that corresponds to your links:

<body class="home">
   <a class="home" href="foo.html">Home</a>
   <a class="contact" href="bar.html">Contact</a>
</body>

In this case, you would select the active link styles like this:

body.home a.home,
body.contact a.contact {
  color: green;
}

This method doesn't require JavaScript to set the initial styles, which is always good.

Comments

0

Use a filter function:

$("#accordion a")
.filter(function(){ 
    return location.href.match($(this).attr("href"))
})
.addClass("active-sidebar-link");

Returns only filtered elements, which in this case would be the link with the current URL and adds the class active-sidebar-link to it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.