user742030
user742030

Reputation:

jQuery Scroll Function Does Not Fire (Scroll Too Fast)

I am seeing that if a user scrolls too fast, the below jQuery function does not fire. Is this a performance issue/bug within jQuery detection of the event or do I need to do something with my code?

...Or, is there a better way [at least performance reliability wise] to call it with pure JavaScript? If so, how do I code it?

        $(window).scroll(function() {
            var st = $(this).scrollTop();
            if(st < 50){
                $('.header_wrapper').css({'marginTop':-50});
            } if(st < 40){
                $('.header_wrapper').css({'marginTop':0});
            }
        });

You can see it in action here: http://www.walkingfish-grainboards.com/privacy-policy/

Thnx for your help - it would be greatly appreciated.

Upvotes: 2

Views: 2667

Answers (2)

user742030
user742030

Reputation:

Well, I over thought it originally. This works great:

$(window).scroll(function(){
yos = (window.pageYOffset > 48);
    $('.headerwrap').toggleClass('stick', yos);
$('.pagetitlewrap').toggleClass('headerwrap_stuck', yos);
});

Upvotes: 0

PlantTheIdea
PlantTheIdea

Reputation: 16359

Since you are considering performance:

$(window).on('scroll',function(){
    var st = $(this).scrollTop(),
        mTop = ((st < 40) ? 0 : -50);

    $('.header-wrapper').css({marginTop:mTop});
});

Rather than put the assignment in the if you can just put the value, then do the assignment once based on the value. With your current statement, the -50px value you remain no matter how far down you go (as you never clear this value), and would only return to 0 when you scrolled back to the top. Hence, you do not need to have the nested if statement.

If you really wanna kick it up a notch, include caching:

var scrollStuff = {
    headerWrapper:$('.header-wrapper'),
    onScroll:function(){
        var self = this,
            st = $(self).scrollTop(),
            mTop = ((st < 40) ? 0 : -50);

        self.headerWrapper.css({marginTop:mTop});
    }
};

$(window).on('scroll',function(){
    scrollStuff.onScroll();
});

By caching everything including the function, you won't need to requery the DOM every time for the element you are applying the marginTop to.

Upvotes: 1

Related Questions