Javascript onscroll event handler

Javascript onscroll event handler can be attach to any DOM element. Attaching it to document is a typical use case. But it can be attached on other DOM Elements like div. Event property event.target can be used to find the target element.

To attach on scroll on document one can use the following code:

document.onscroll = function (event) {}
document.addEventListener("scroll", function(event) {});

Scroll event handler example on document

Here is an example of onscroll handler on document. In handler code, we are setting onscroll to null. So handler code will execute only once.

<style type="text/css">
#id1 {min-height: 1600px;}
</style>
<div id="id1">==Scroll this document==<br/></div>

<script type="text/javascript">
document.onscroll = function(e) {
  document.querySelector("#id1").innerHTML += "target=" + e.target + "<br/>";
  e.target.onscroll = null;
}
</script>
refresh

Scroll event handler example on div

Here is an example of onscroll handler on a div. In handler code, we are setting onscroll to null. So handler code will execute only once.

<style type="text/css">
#outer {height:100px; width:300px; background-color:lightgreen;overflow: scroll;}
#id1 {min-height: 600px; width:2500px;}
</style>
<div id="outer">
<div id="id1">==Scroll this div==<br/></div>
</div>

<script type="text/javascript">
document.querySelector("#outer").onscroll = function(e) {
  document.querySelector("#id1").innerHTML += "target=" + e.target + "<br/>";
  e.target.onscroll = null;
}
</script>
refresh

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments