npm install scrollwatchbower install scrollwatchInclude the library on your page.
<script src="ScrollWatch.js"></script>Create a new ScrollWatch instance and pass in an options object with an onElementInView callback. By default, ScrollWatch will fire your callback when any elements with a data-scroll-watch attribute come into view. Check out the API section below for all options.
var sw = new ScrollWatch({
onElementInView: function(data) {
console.log(data.el, '...is now in view');
}
});You can create as many instances of ScrollWatch as you need. The constructor accepts an options object, allowing you to customize your instance. Save a reference to the new instance if you want to call any of the public methods at a later time.
var sw = new ScrollWatch({
/* options */
})Below are all of the options you can pass to ScrollWatch and their default values:
container: window.document.documentElementwatch: '[data-scroll-watch]'watchOnce: trueignoreClass: 'scroll-watch-ignore'inViewClass: 'scroll-watch-in-view'debounce: falsedebounceTriggerLeading: falsescrollDebounce: 250resizeDebounce: 250scrollThrottle: 250resizeThrottle: 250watchOffsetXLeft: 0watchOffsetXRight: 0watchOffsetYTop: 0watchOffsetYBottom: 0onElementInView: function(obj){}eventTypeeldirectiononElementOutOfView: function(obj){}infiniteScroll: falseinfiniteOffset: 0onInfiniteYInView: function(obj){}eventTypedirectiononInfiniteXInView: function(obj){}Below are the public methods available on each ScrollWatch instance:
refresh()destroy()updateWatchOffsetXLeft(offset)updateWatchOffsetXRight(offset)updateWatchOffsetYTop(offset)updateWatchOffsetYBottom(offset)pauseInfiniteScroll()resumeInfiniteScroll()ScrollWatch is only limited by your imagination! Below are some demos that outline the basic building blocks of a ScrollWatch interaction.
Fades in elements when they come into view the first time.
See the Pen Fade In Elements Once by Evan Dull (@edull24) on CodePen.
Fades in elements when they come into view every time.
See the Pen Fade In Elements Every Time by Evan Dull (@edull24) on CodePen.
Fades in elements in a container other than "window" when they come into view the first time.
See the Pen ScrollWatch.js Demo: Nested Watching by Evan Dull (@edull24) on CodePen.
Injects new elements into the page when you get 200px from the bottom of the page.
See the Pen ScrollWatch.js Demo: Infinite Scrolling by Evan Dull (@edull24) on CodePen.