patik/within-viewport

constant measurement

burgessa23 opened this issue · 1 comments

Hi,
is it possible to constantly measure viewport state while scrolling?
currently it seems that in/out state is only tested on scroll end

-Thanks

You can measure constantly by binding to the window.onscroll event but I highly discourage it.

  1. It's very taxing on the browser and CPU and can lead to major performance issues. When the user scrolls with the mouse they tend to scroll several dozens of pixels at a time which means any code bound to that event will run several dozens of times. When you're running a script that depends on the DOM, like Within Viewport, the performance takes an even bigger hit. You can read more about why binding to onscroll is a bad practice.
  2. Many mobile browsers will not fire the scroll event until the scrolling has stopped (including any momentum/inertia that occurs after lifting your finger from the screen). So if you design your site to constantly update as the user scrolls you may not see the desired effect equally across all browsers.

I recommend using the jQuery scrollStop plugin as mentioned in the readme. (Unfortunately I don't know of a vanilla JS version.)

However if you understand the caveats and want to plunge forward regardless, you can bind to the scroll event like this:

window.addEventListener('scroll', function(evt) {
    if (withinViewport(someElement)) {
        // Element is within the viewport, do something here...
    }
}, false);