cusejuice
cusejuice

Reputation: 10681

jQuery window scroll stop firing as user scrolls

When the user scrolls down a certain number of pixels, I fix the header. However, is there a way to stop calling the window scroll function after the user satisfies the logic in place? I assume that this is not good for performance. See screenshot of my console (http://d.pr/i/OHDX)

$window.scroll(function() {
    if ($window.scrollTop() > 100) {
        $('.header').addClass('fixed');
        console.log('fix header'); 
    }
    else {
        $('.header').removeClass('fixed');
        console.log('unfix header'); 
    }

}

Upvotes: 0

Views: 182

Answers (1)

Halcyon
Halcyon

Reputation: 57709

You have to keep checking the scroll position. I assume you'll want to unfix it when the user scrolls back up to 100?

Your current implementation is fine, performance-wise. One thing you could add is a check to see if the class isn't already added, or keep a toggle so you know if the class is there (instead of checking).

$window.scroll((function() {
    var fixed = false, elem;
    return function () {
        var should_fix = $window.scrollTop() > 100;
        elem = elem || $('.header');
        if (should_fix !== fixed) {
            if (should_fix) {
                elem.addClass('fixed');
                console.log('fix header'); 
            } else {
                elem.removeClass('fixed');
                console.log('unfix header'); 
            }
            fixed = should_fix;
        }
    };
}()) // immediate invocation, because it's awesome

Upvotes: 3

Related Questions