Help a jquery-noob with some scroll events

Hi,

I have this:

$(window).scroll(function() {
    var window_top = $(window).scrollTop();
    var div_top = $('.filter-anchor').offset().top + 300;
    if (window_top > div_top) {
        $('#filter').addClass('stick-filter');
        $('.filter-filler').show();
    } else {
        $('#filter').removeClass('stick-filter');
        $('.filter-filler').hide();
    }
});

$("#tofilter").click(function(e) {
    e.preventDefault();
    $('.stick-filter').toggleClass('filter-state');
});

I have a div that is fixed after scrolling past it + 300px. You can also see that I have a click function that toggles the class .filter-state on the fixed div.

BUT, I also want to remove the class .filter-state when I scroll UP, like after 50-100px from the current position.

How can I do this?

Basically, you want to record the direction of the scroll scroll.dir.cur. If you’re still going in the same direction scroll.dir.cur === scroll.dir.last, then add that distance to the total distance traveled scroll.dist, otherwise reset the distance traveled counter.

Once the total distance traveled is greater than 50 scroll.dist > scroll.unstickDist, then you remove the class. I haven’t tested it, but here’s what it should look like. Let me know if it doesn’t work at all (check the console, I might have made a typo) and I’ll come up with an example.

var $window     = $(window)             // Cache
var scroll = {
    // Scroll Directions: -1=up, 1=down
    dir: {
        last:   1,  // What was it during the last step?
        cur:    1   // What is it now?
    },
    lastTop: $window.scrollTop(),   //The last scrollTop, used to determine distance scrolled
    dist: 0,        // Number of pixels scrolled in the same direction (resets if scroll direction changes)
    unstickDist: 50 // How many pixels before we unstick. Change this to whatever you'd like
}

/**
 * Scroll Event
 */
$window.scroll(function() {
    var window_top = $window.scrollTop();
    var div_top = $('.filter-anchor').offset().top + 300;
    if (window_top > div_top) {
        $('#filter').addClass('stick-filter');
        $('.filter-filler').show();
    } else {
        $('#filter').removeClass('stick-filter');
        $('.filter-filler').hide();
    }

    // Set the scroll direction
    scroll.dir.cur = (scroll.lastTop < window_top) ? 1 : -1

    // Add current scrolled distance
    if(scroll.dir.cur === scroll.dir.last)
        scroll.dist += Math.abs(scroll.lastTop - window_top)    // Add distances absolutely

    // Remove stick filter if scrolled beyond scroll.unstickDist
    if(scroll.dist > scroll.unstickDist){
        $('#filter').removeClass('stick-filter')
        $('.filter-filler').hide()
    }

    // Update the last scrolled top
    scroll.lastTop = window_top
});

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.