Javascript DOM HTML Element scrollTop Property

Introduction

The scrollTop property sets or gets the number of pixels an element's content is scrolled vertically.

The following code gets the number of pixels the content of a <div> element is scrolled horizontally and vertically:

Scroll inside the div element to display the number of pixels the content of div is scrolled horizontally and vertically.

View in separate window

<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {/*  w  ww . j  a v  a2  s .  c  o  m*/
  height: 250px;
  width: 250px;
  overflow: auto;
}

#content {
  height: 800px;
  width: 2000px;
  background-color: coral;
}
</style>
</head>
<body>
<div id="myDIV" onscroll="myFunction()">
  <div id="content">Scroll inside me!</div>
</div>

<p id="demo"></p>

<script>
function myFunction() {
  var elmnt = document.getElementById("myDIV");
  var x = elmnt.scrollLeft;
  var y = elmnt.scrollTop;
  document.getElementById ("demo").innerHTML = "Horizontally: " + x + "px<br>Vertically: " + y + "px";
}
</script>

</body>
</html>

Use the scrollLeft property to set or return the number of pixels an element's content is scrolled horizontally.

To add scrollbar to an element, use the CSS overflow property.

The onscroll event occurs when an element's scrollbar is being scrolled.

The scrollTop property returns a Number representing the number of pixels that the element's content has been scrolled vertically.




PreviousNext

Related