The scroll monitor allows you to receive events when elements enter or exit the viewport. It does this using watcher objects, which watch an element and trigger events. Watcher objects also contain information about the element they watch, including the element's visibility and location relative to the viewport.

The scroll monitor was designed to be very fast. On each scroll event the DOM is only touched twice, once to find the document height and again to find the viewport top. No variables are declared, nor are any objects, arrays, or strings created.

The code is based on vanilla javascript and has no external dependencies. Except if you want to put it in the head of the document, then you'll need jQuery for the DOMContentLoaded event.

stateChange - similar to visibilityChange but is also called if the element goes from below the viewport to above it in one scroll event or when the element goes from partially to fully visible or vice versa.

enterViewport - when the element enters the viewport.

fullyEnterViewport - when the element is completely in the viewport [1].

exitViewport - when the element completely leaves the viewport.

partiallyExitViewport - when the element goes from being fully in the viewport to only partially [2].

If the element is larger than the viewport fullyEnterViewport will be triggered when the element spans the entire viewport.

If the element is larger than the viewport partiallyExitViewport will be triggered when the element no longer spans the entire viewport.

Sometimes you want to change the element you're watching, but want to continue watching the original area. One common use case is setting position: fixed on an element when it exits the viewport, then removing positioning when it when it reenters.

var watcher = scrollMonitor.create( $element );

watcher.lock();// ensure that we're always watching the place the element originally was

watcher.exitViewport(function(){

$element.addClass('fixed');

});

watcher.enterViewport(function(){

$element.removeClass('fixed');

});

Because the watcher was locked on the second line, the scroll monitor will never recalculate its location.