How to scroll to position on an element in Javascript?
To get or set the scroll position of an element, you follow these steps:
1. First, select the element using the selecting methods such as querySelector() .
2. Second, access the scroll position of the element via the scrollLeft and scrollTop properties.
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>