A small JavaScript library for scroll-based data-driven graphics (without any nasty scrolljacking). scrollWatcher sticks an element at a fixed position onscreen, and then provides the distance scrolled through its (much taller) parent as a percentage.
As seen on WSJ.com in How Fed Rates Move Markets and What ECB Stimulus Has Done.
- Want something to always stick on the page? Use CSS
position: fixed;. - Want something to stick when you scroll past it? Use jQuery fixto plugin or jQuery Sticky.
- Want a sticky header that hides on scroll? Use headroom.js.
- Want to trigger events on scroll? Use Waypoints.
- If you want to use scroll as a way of interacting with a data-driven graphic without scrolljacking, use scrollWatcher.
Include jQuery and the sticky-positioning fixto plugin on the page.
In your HTML, you'll need a tall outer element, with one much shorter element inside of it.
<divclass="outer" style="height: 2000px;"><divclass="inner"></div></div>
In your JavaScript, you'll need to call
scrollWatcherwith a configuration object usingparentandonUpdatearguments. The function passed intoonUpdatewill run every 20 miliseconds.scrollWatcher({parent: '.outer',onUpdate: function(scrollPercent,parentElement){$('.inner').text('Scrolled '+scrollPercent+'% through the parent.');}});
Check out the source code to see how these are used.
If you create a new instance of scrollWatcher:
varmyWatcher=scrollWatcher({onUpdate: function(scrollPercent,parentElement){console.log('Scrolled '+scrollPercent+'% through the parent.');},parent: '.outer'});... you can then start, pause and stop at any time.
// stop checking but keep stuckmyWatcher.pause();// stop checking and unstickmyWatcher.stop();// start checking and restickmyWatcher.start();There are two read-only properties:
activeis true when the scrollWatcher instance is currently onscreen (and running).varisActive=myWatcher.active;
hasBeenActiveis true when the scrollWatcher instance has been onscreen (and run) at least once.varisOrWasActive=myWatcher.hasBeenActive;
You may want to use these to (for example) hide a "keep scrolling!" message.
Use scrollWatcher.supported() to check whether or not scrollWatcher will work in the current browser.
scrollWatcher works on all modern browsers, including IE 9 and up. However, it does not work on iOS 7 and lower due to the way Safari handles CSS position: fixed;.
To run tests, open tests.html in your browser and wait a couple of seconds.
v1.0.0 (April 19, 2016)
- Initial public release