How to Get the Scrollbar Position With JavaScript
- What Is Scrollbar and Scrollbar Position
-
Get the Scrollbar Position Using the
window
Object in JavaScript - Get the Scrollbar Position Inside an Element in JavaScript
In this tutorial, we will discuss how to get the scrollbar position in JavaScript, and we will discuss:
- What is scrollbar and scrollbar positon
- How to get the scrollbar position using the
window
object - How to get the scrollbar position inside an element
What Is Scrollbar and Scrollbar Position
A rectangular-shaped bar is usually on the bottom-most or rightmost end of the browser window that the user can scroll, which in return positions the user’s viewing area. Many users use the scrollbar daily because they need to scroll up and down on almost every webpage to view more content.
The scrollbar is the horizontal or vertical position of the window’s viewing area, meaning how much the user has scrolled from the left or the top. By default, the scroll position is 0px
from the left and 0px
from the top.
Get the Scrollbar Position Using the window
Object in JavaScript
We can get the scrollbar position on the window using the window
object. Since the window
object is like any other JavaScript object, we can add an EventListener to listen to a scroll
event.
window.addEventListener('scroll', (event) => {
let scrollY = this.scrollY;
let scrollX = this.scrollX;
console.log(scrollY);
console.log(scrollX);
});
this
in this context is referred to as window
object. scrollY
is a property of window
that tells us the number of pixels the window viewing area has been scrolled from the top. scrollX
is a property of window
object that tells us how much the user has scrolled from the left.
Get the Scrollbar Position Inside an Element in JavaScript
There are certain scenarios where you would need to get the scroll position not of the entire window but relative to an element. Let’s take a look at an example of doing this.
<!DOCTYPE html>
<html>
<head>
<style>
#ContentContainer {
height: 250px;
width: 250px;
overflow: auto;
}
#content {
height: 500px;
width: 1000px;
background-color: red;
}
</style>
</head>
<body>
<div id="ContentContainer" onscroll="getScrollPoistion()">
<div id="content">Content to Scroll</div>
</div>
<script>
function getScrollPoistion() {
var ContainerElement = document.getElementById("ContentContainer");
var x = ContainerElement.scrollLeft;
var y = ContainerElement.scrollTop;
console.log(x); // scroll position from Left
console.log(y); // scroll position from top
}
</script>
</body>
</html>
In the code segment above, the element having the id
of ContentContainer
has a property of onscroll
; whenever a user scrolls inside the element, the getScrollPosition
function is executed.
What getScrollPosition
does is that it takes the container of the content element, and it gets the position it has been scrolled from the left, and then it gets the position scrolled from the top.