简体   繁体   中英

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

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/

Try this:

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

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

Check JSFiddle Demo

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');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM