Remove class when browser scrolls down, but adds class when it scrolls up

I am creating a one page site, I want to remove the class when the user scrolls down and add the class when the user scrolls down.

It works for me, but it is not correct, the moment the user scrolls down 50px from the top, the class is removed and added when the user scrolls up 50px from the top.

I want them to be almost at the bottom of the page, and if there is a scroll up the class, and if they scroll down, they are removed

Here's the query I have so far

jQuery(document).ready(function($) {
    $(".test").addClass("mobile");
    $(window).scroll(function(){
        var scroll = $(window).scrollTop();
        if (scroll >= 50) {
        $(".test").removeClass("mobile");
        } else if (scroll <= 50) {
        $(".test").addClass("mobile");
        }
    });
});

      

+3


source to share


1 answer


So this declares a global variable lastScroll to keep track of the last known scroll position. After the user scrolls, it compares the scroll location to the last known scroll location and adds or removes your class depending on that. I also removed the <= and> = because I didn't want it to do anything unless the scroll position changed (somehow).

var lastScroll = 0;

jQuery(document).ready(function($) {
    $(".test").addClass("mobile");

    $(window).scroll(function(){
        var scroll = $(window).scrollTop();
        if (scroll > lastScroll) {
            $(".test").removeClass("mobile");
        } else if (scroll < lastScroll) {
            $(".test").addClass("mobile");
        }
        lastScroll = scroll;
    });
});

      



In the comments below, add the following:

var lastScroll = 0;

jQuery(document).ready(function($) {
    $(".test").addClass("mobile");

    $(window).scroll(function(){
        setTimeout(function() { //give them a second to finish scrolling before doing a check
            var scroll = $(window).scrollTop();
            if (scroll > lastScroll + 30) {
                $(".test").removeClass("mobile");
            } else if (scroll < lastScroll - 30) {
                $(".test").addClass("mobile");
            }
            lastScroll = scroll;
        }, 1000);
    });
});

      

+6


source







All Articles