Dan
Dan

Reputation: 1660

Remove class when browser scrolls down but add class when it scrolls up

I'm creating a 1 page website, I want to remove a class when the user scrolls down and add the class when the user scrolls up.

I've got this working to a point but it's not correct, at the moment when the user scrolls down 50px from the top then the class is removed and it's added when the user scrolls up 50px from the top.

I want it so that they can be almost at the bottom of the page and if the scroll up the class is there and if they scroll down then it's 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");
        }
    });
});

Upvotes: 6

Views: 6575

Answers (1)

C Bauer
C Bauer

Reputation: 5103

So this declares a global variable lastScroll to track the last known scroll position. After the user scrolls, it will compare the scroll location to the last known scroll location and add or remove your class depending on that. I also removed the <= and >= because I didn't want it to do anything if the scroll position doesn't change (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;
    });
});

Per the comments below, add this:

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

Upvotes: 9

Related Questions