How to add a class when reaching a certain element at the top of the page and delete it?

Viewed 1294

This is my code:

jQuery(document).ready(function($){
    $(window).on('scroll', function(){
        if($(window).scrollTop() >= $('#element').offset().top){
            $('.menu').addClass('addclass');
        }
    });
});

It adds addclass to the menu when reaching id = "element" at the top of the page and scrolling further to the bottom.

But how to remove addclass when id = "element" is again below the top of the pages.

2 Answers

Simply use toggleClass or removeClass:)

jQuery(document).ready(function($){
    $(window).on('scroll', function(){
        if($(window).scrollTop() >= $('#element').offset().top){
            $('.menu').addClass('addclass');
        }
        else 
        {
            $('.menu').toggleClass('addclass');
            //or use $('.menu').removeClass('addclass');
        }
 });
});

Just do the reverse:

jQuery(document).ready(function($){

        $(window).on('scroll', function(){
            if($(window).scrollTop() < $('#element').offset().top){
              $('.menu').removeClass('addclass');
            }
          });
    });
Related