0

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?

neoDev
  • 2,879
  • 3
  • 33
  • 66
  • 1
    Unfortunately this isn't possible. For performance reasons the value is read each time the UI is updated, not when each pixel is scrolled. This means that pixels will be skipped between updates. There is nothing you can do about this. To fix this you could use CSS `transition` on the `opacity` value to make the adjustment smoother – Rory McCrossan Oct 14 '16 at 09:44
  • Oh that sounds bad... :( At this point I don't know what to do – neoDev Oct 14 '16 at 09:46

1 Answers1

2

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.

Jesse
  • 429
  • 6
  • 12
  • Thank you, as @Rory already mensioned I could use css transitions to "masquerade" the pixel loss, but even if this could be ok for my actual project, it is not ok in other situations e.g. move an element – neoDev Oct 14 '16 at 09:53
  • 1
    @neoDev you can get silky smooth positioning if you use both transform + transition css rules. – Jesse Oct 14 '16 at 09:57
  • Yes I know but sometime I will definitely need to use this without any transition. – neoDev Oct 14 '16 at 09:59