Summary: in this tutorial, you’ll learn how to get or set the scroll position of an element using the Element.scrollTop
and Element.scrollLeft
properties.
To get or set the scroll position of an element, you follow these steps:
- First, select the element using the selecting methods such as
querySelector()
. - Second, access the scroll position of the element via the
scrollLeft
andscrollTop
properties.
The Element.scrollTop
gets or sets the number of pixels that an element’s content is scrolled vertically.
The Element.scrolLeft
gets or sets the number of pixels that an element’s content is scrolled from its left edge.
Note that the top left corner of the element is (0, 0)
. The scrollLeft
and scrollTop
are relative to that coordinate.
The following example illustrates how to get the scroll position of the element with the id #scrollDemo
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Get/Set Scroll Position of an Element</title>
<style>
#scrollDemo {
height: 200px;
width: 200px;
overflow: auto;
background-color: #f0db4f
}
#scrollDemo p {
/* show the scrollbar */
height: 300px;
width: 300px;
}
</style>
</head>
<body>
<div id="scrollDemo">
<p>JavaScript scrollLeft / scrollTop</p>
</div>
<div class="output"></div>
<script>
const scrollDemo = document.querySelector("#scrollDemo");
const output = document.querySelector(".output");
scrollDemo.addEventListener("scroll", event => {
output.innerHTML = `scrollTop: ${scrollDemo.scrollTop} <br>
scrollLeft: ${scrollDemo.scrollLeft} `;
}, { passive: true });
</script>
</body>
</html>
Code language: HTML, XML (xml)
Was this tutorial helpful ?