npm install scrollwatch
bower install scrollwatch
Include 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.documentElement
watch: '[data-scroll-watch]'
watchOnce: true
ignoreClass: 'scroll-watch-ignore'
inViewClass: 'scroll-watch-in-view'
debounce: false
debounceTriggerLeading: false
scrollDebounce: 250
resizeDebounce: 250
scrollThrottle: 250
resizeThrottle: 250
watchOffset: 0
onElementInView: function(obj){}
eventType
el
direction
onElementOutOfView: function(obj){}
infiniteScroll: false
infiniteOffset: 0
onInfiniteYInView: function(obj){}
eventType
direction
onInfiniteXInView: function(obj){}
Below are the public methods available on each ScrollWatch instance:
refresh()
destroy()
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.