简体   繁体   中英

Remove class from element when not shown in viewport

I am making a site that has fixed secondary navigation to the right side of the viewport. Using Waypoints I have been able to add a class to my navigations anchor elements when a specific id appears in the bottom of the viewport. What I don't know how to do however, is to remove that class from that element when the element in no longer in the viewport. Right now my navigation will get the proper styling from the active class but each navigation element will keep the active class styling as I scroll down the page. I need to remove the active class when the element is no longer shown on the screen. Thank you for any help.

jQuery:

$("#logo").waypoint(function(){
    $("#logo-nav").addClass('active');
});

$("#design").waypoint(function(){
    $("#design-nav").addClass('active');
});

$("#outdoor").waypoint(function(){
    $("#outdoor-nav").addClass('active');
});

$("#online").waypoint(function(){
    $("#online-nav").addClass('active');
});

$("#photo").waypoint(function(){
    $("#photo-nav").addClass('active');
});

$("#video").waypoint(function(){
    $("#video-nav").addClass('active');
});

live html page:

http://dai1.designangler.com/work

Add this line before each addClass() :

$('.active').removeClass('active');

If you give your waypoint elements a common class, then you can replace all the code above with:

$(".waypoint-element").waypoint(function(){
    $('.active').removeClass('active');
    $('#' + this.id + '-nav').addClass('active');
});

You can just remove the active class from all nav-links when a waypoint is reached, and then add it to the currently active one.

var setActive = function(id) {
    $(".nav > a").removeClass('active');
    $(id).addClass('active');
}

$("#logo").waypoint(function(){
    setActive("#logo-nav");
});
// ...

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