Amir
Amir

Reputation: 537

Highlight the active anchor link

I have 2 navigation beside each other, they are using anchor links, i want to highlight active link once it is clicked.

What i did is

$('.navyy li').click(function() {
    $(this).addClass('highlight').siblings('li').removeClass('highlight');
});

and the HTML is

 <div class="navyy">
<ul id="nav">
    <li><a href="#top">Introduction</a></li>
    <li><a href="#bookmark1">Usability vs Functionality</a></li>
    <li><a href="#bookmark2">99/100 Google PageSpeed!</a></li>
</ul>
<ul id="nav">
     <li><a href="#bookmark3">Gravatar Caching!</a></li>
    <li><a href="#bookmark4">Optimize Images First!</a></li>
    <li><a href="#bookmark5">Rich Snippets Boost CTR</a></li>
</ul>
    </div>

It seems the jQuery is just active on of the UL if you click on one of the item in first nav it will be highlight, but if you select another item from other nav the first selected item will be remain highlighted.

Here is my JSFIDDLE example

Thanks

Upvotes: 1

Views: 3448

Answers (3)

Moshtaf
Moshtaf

Reputation: 4903

Try this:

var $navyyLi = $(".navyy li");

$navyyLi.click(function() {
  $navyyLi.removeClass('highlight')
  $(this).addClass('highlight');
});

Check JSFiddle Demo

Upvotes: 1

Jason
Jason

Reputation: 4159

Similar to other answers, but more efficient. jQuery isn't having to query the DOM on each click. In this case, the elements are cached for future use.

var naavy = $(".navyy li");

naavy.click(function() {
    naavy.removeClass("highlight");
    $(this).addClass('highlight');
});

http://jsfiddle.net/hLeQy/89/

If you don't need to support old browsers, you can easily do it without jQuery:

var naavy = document.querySelectorAll(".navyy li");
var length = naavy.length;

for(var i=0; i<length; i++) {
    naavy[i].addEventListener("click", function() {
        highlight(this);
    });
}

function highlight(element) {
    for(var i=0; i<length; i++) {
       naavy[i].classList.remove("highlight");
    }

    element.classList.add("highlight");
}

http://jsfiddle.net/hLeQy/90/

Upvotes: 3

Jason Goemaat
Jason Goemaat

Reputation: 29234

Elements are sibling only if they have the same parent so you are only removing the highlight class from LI elements with the same UL parent. If you want to remove all the highlights no matter where they are, you can do that first. The only problem would be if you animate on adding the highlight, then you should check that it isn't already highlighted first. (fiddle)

$('.navyy li').click(function() {
    $('.navyy li').removeClass('highlight');
    $(this).addClass('highlight');
});

Upvotes: 1

Related Questions