简体   繁体   中英

Apply the class “active” to nav links when clicked?

My website is a parallax one page scrolling website, so all my nav links are directed to ids nested within that page...

For example:

<ul class="clearfix">
    <li><a href="index.html" class="active">Home</a></li>
    <li><a href="#portfolio">Work</a></li>
    <li><a href="#about">About</a></li>
    <li><a href="#contact">Contact</a></li>
</ul>

So How would I tell my html that when someone clicks on one of these links and directs them to the corresponding ID on the page, to take on the class active? And the link that was active to turn back to the regular styling?

Assuming your link elements are contained in an element with class nav , and you're using jQuery, you could do the following:

$('.nav a').on('click', function(event) {
    $('.nav a.active').removeClass('active');
    $(this).addClass('active');
});

fiddle

jQuery

$('ul a').on('click', function(event) {
    $('a').removeClass("active");
    $(this).addClass("active");
});

Replace ul a with something more specific like .nav a

You will have to use JavaScript to add that functionality into your application. Everytime a link is clicked, add the 'active' class to the triggering element, and remove it from all others. This is straightforward if you can use jQuery ( jsFiddle with jQuery ), and only a little more tedious otherwise.

$(function() {
    $("ul.clearfix > li > a").click(function() {
        $("a.active").removeClass("active");
        $(this).addClass("active");
    });
});

If you're only using native JS, you can try something along the lines of the below ( jsFiddle using vanilla JS ):

var links = document.getElementsByTagName("a"); // more specific selector if other links
for (var i = 0; i < links.length; i++) {
    var link = links[i];
    link.onclick = function () {
        var prev = document.getElementsByClassName("active");
        if (prev && prev[0]) {
            prev[0].className = ""; // if using other classes, filter better
        }
        this.className += " active";
    };
}

This second solution needs to be adapted to fit your particular application/DOM structure, since it's not quite as flexible as the first.

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