jQuery scrollTop() precision when fast scrolling the page (avoid pixels loss)

704 views Asked by At

I am using jQuery scrollTop() value to change an element opacity on page scroll

$(document).on('scroll', function(){
    if($(document).scrollTop() >= 1 ){
        $('#elem').css({'opacity': ($(document).scrollTop() * 0.02)});
    }
});

it works fine but the problem is that if I scroll the page fastly it 'skips' a lot of pixels, resulting in an ugly effect because the returned pixels are e.g.

0
30
50
80
90
...

and not

0
1
2
3
4

like when I slowly scroll...

Also another time I had the same problem, where I needed smooth values but this "pixel skipping" behaviour complicated things...

How can I solve this?

1

There are 1 answers

3
Jesse On

If you want things to be smooth you should add a CSS transition to the element. So that even if the scroll jumps from 0 to 500 the transition will remain smooth.

#elem {
    -webkit-transition: opacity 0.5s ease;
    -moz-transition: opacity 0.5s ease;
    transition: opacity 0.5s ease;
}

Trying to achieve smooth pixel values in jQuery alone wont work.