neoDev neoDev - 5 months ago 12
Javascript Question

jquery onscroll skips values when hard scroll

I am updating a div position using jQuery 'scroll' event

It works fine when I scroll slowly, but when I scroll quickly it skips some

$(window).scrollTop()
values, so at the end the div results misaligned

$(window).on('scroll', function(){
var scroll = $(window).scrollTop();
if(scroll > 0 && scroll < 60){
$('#div').css('top', 80 - scroll+'px');
}
console.log( scroll );
});


How can I do?

Answer

A way to solve this is to not just set it when you're scrolling in a certain range of pixels, but also to set it at the bounds, like this:

$(window).on('scroll', function(){
    var scroll = $(window).scrollTop();
    if(scroll > 0 && scroll < 60){
        $('#div').css('top', 80 - scroll+'px');
    } else if ( scroll <= 0 ) {
        $('#div').css('top', '80px');
    } else {
        $('#div').css('top', '20px');
    }
    console.log( scroll );
});

The problem occurs because the browser is trying to save processing power. After all, if you're gonna move 10 pixels in one frame, why render 10 times? Just render one frame and be done.

So it'll say "Hey I've moved to pixel 10" rather then "I've moved to 1", "I've moved to 2", "I've moved to 3, etc".

This has the effect that it can go from, say, 50 to 70 in one frame and leave you effectively stuck at 50. Because you were just throwing away the 70 message for 70 pixels. With this code you are treating the 70 pixels message as, basically, a 60 pixels message.