Javascript DOM HTML Element scrollLeft Property

Introduction

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

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 w w.  j av  a2s  .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 scrollTop property to set or return the number of pixels an element's content is scrolled vertically.

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

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




PreviousNext

Related