jlmakes / scrollreveal

Animate elements as they scroll into view.
https://scrollrevealjs.org/
22.39k stars 2.26k forks source link

javascript scroll to element became glitchy and buggy when use distance option #476

Closed sunchayn closed 5 years ago

sunchayn commented 5 years ago

Hi there,

Thanks for this awesome library.

I want to use on scroll event to detect if an element is partially visible; if it is visible in the viewport, scroll to the top offset of this element.

The code I wrote seems to work fine, but when I use options.distance I get strange behavior: The element that I want to scroll to becomes glitchy and sometimes the the scrollIntoView does not work quite right...

I think it's almost working, but ScrollReveal reverts the scroll offset to it's previous position causing the glitches. Check out the demo: https://jsbin.com/vukoqasemo/1/edit?html,js,output

In the demo it occurs randomly, but on my web page, it occurs more often and more aggressively.

jlmakes commented 5 years ago

I appreciate your patience @mazentouati

I've run into this problem before!

getBoundingClientRect() includes CSS transforms applied to the element in the return value.

So when using options.distance to move your element visually by 20px, you are actually changing the position of that element as far as getBoundingClientRect() is concerned. Arguably this is a good feature: we can get the true rendered position of our elements!

The problem is that we are animating CSS transforms... which means getBoundingClientRect() will give different size/position information depending on the progress of the animation!! This is where the "glitchy behavior" comes from.

This is actually the reason ScrollReveal does not use getBoundingClientRect() internally to check element positions! Check out how ScrollReveal does this using getGeometry, which returns element size/position without factoring in CSS Transforms.

In short, you'll need another way to check element positions!