Adam
Adam

Reputation: 2997

jQuery addClass Issue - trying to find an element by ID

I have a menu which links to anchors on the page. There are a couple of additional pages that can also link back to the home page with these anchors on.

I have some jQuery which changes the color of a menu item when it clicked. So if I click on About on the homepage, it goes to the about anchor and highlights about in blue. If I click on about from the blog page though, it goes to the home page, and the about anchor but it doesn't highlight the menu item as that jQuery is only triggered by a click event. I am trying to therefore manually trigger the highlight when page loads if it sees an anchor in the URL.

The HTML is:

<ul id="navigation">
  <li id="item_0"><a href="#home" class="active">Home</a></li>
  <li id="item_1"><a href="#about">About</a></li>
  <li id="item_2"><a href="#projects">Projects</a></li>
  <li id="item_3"><a href="#locate">Locate</a></li>
  <li id="item_4"><a href="/blog">Blog</a></li>
</ul>

As you can see - the class="active" is applied to < a> tag of the active menu item.

I'm trying to use the following jQuery JS to check on page load for anchor tags, and highlight the relevant one.

$(document).ready(function(){
    var hash = window.location.hash;

    switch(hash){
        case "#about":
            $('#navigation li a').removeClass("active");
        $('item_1', '#navigation li a').addClass('active');
         break;
    }
});

Can anyone help with whats going wrong?

Thanks in advance for your help!

Upvotes: 1

Views: 3342

Answers (3)

hunter
hunter

Reputation: 63512

This selector is wrong: $('item_1', '#navigation li a'). What that's doing is looking for an item_1 element (doesn't exist) within the #navigation li a selector (which will select the anchor tags).


Try this instead. You also won't need any messy switch statement

$(function(){
    var hash = window.location.hash;

    $('#navigation li a').removeClass("active");
    $('#navigation li a[href=" + hash + "').addClass("active");
});

You may want to handle a base case if no anchor was clicked.

Upvotes: 0

karim79
karim79

Reputation: 342625

You can just simulate a mouse click instead to avoid duplication of your highlighting code:

var hash = window.location.hash;
if(hash) {
    $("a[href='" + window.location.hash + "']").click();
}

Upvotes: 0

user113716
user113716

Reputation: 322452

To select by ID, change this:

$('item_1', '#navigation li a').addClass('active');

to this (since IDs must be unique, you don't need a more complex selector):

$('#item_1 a').addClass('active');

The id-selector[docs] requires a #.

Upvotes: 3

Related Questions