Scroll Event
There's a scroll
event you can use. When you scroll the page or an element, this event occurs repeatedly while scrolling.
scroll
event occurs on both window
and elements.
Here is an example -
<script type="text/javascript">
window.addEventListener("scroll", function(event){
console.log(window.pageYOffset + "px");
});
</script>
Here is an example on an element -
<div id="demo1" style="border: 1px solid #333; height: 100px; width: 400px; overflow-y: auto;">
<ul>
<li>Hello</li>
<li>Hello</li>
<li>Hello</li>
...
</ul>
</div>
<script type="text/javascript">
demo1.onscroll=function(event){
console.log(event.target.scrollTop);
};
</script>
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
- Hello
There are some pretty good application you can do with the scroll event -
- display Scroll to Top button when the user scrolls down some amount.
- Load image when they are only in the viewport, otherwise use default image as a placeholder. This saves lots of traffic.
- Push the content at the bottom when the user reaches at the bottom. Useful for pushing search result.
- And many more.