Sometimes, we may want to get the position of the scrollbar when we’re scrolling on an element or page.
In this article, we’ll look at how to get the scrollbar position with JavaScript.
Using the scrollTop Property of an Element
We can use the scrollTop
property of an element to let us get the number of pixels hidden because of scrolling.
So we can use this to get the position of the scrollbar.
For instance, we can write the following HTML:
<div>
</div>
Then we can listen to the scroll event by writing:
const div = document.querySelector('div')
for (let i = 1; i <= 100; i++) {
const p = document.createElement('p')
p.textContent = i
div.appendChild(p)
}
window.addEventListener('scroll', (e) => {
console.log(document.documentElement.scrollTop);
})
We get the div with the document.querySelector
method.
Then we add 100 p elements into the div by calling document.createElement
to create the elements.
And we set the content of each by setting the textContent
property.
Then we append it to the div with the div.appendChild
method.
Next, we call window.addEventListener
with the 'scroll'
string as the first argument to listen to the scroll event.
And then we can get the scrollTop
property of the documentElement
to get how far the html
element has scrolled down.
We can also get the scrollTop
property of other elements.
For instance, if we have:
<div style='height: 300px; overflow-y: auto'>
</div>
We set the height
and overflow-y
properties to make the div scrollable.
Then we can listen to the scroll
event of the div by writing:
const div = document.querySelector('div')
for (let i = 1; i <= 100; i++) {
const p = document.createElement('p')
p.textContent = i
div.appendChild(p)
}
div.addEventListener('scroll', (e) => {
console.log(div.scrollTop);
})
We add the content to the div like we have before.
But we call div.addEventListener
instead of window.addEventListener
to listen to the scroll
event of the div.
Then we get the div.scrollTop
property to get how far the div has scrolled down.
Using the scrollY Property of the window Object
There’s also the window.scrollY
property to let us get how far down the scrollbar is in pixels.
For instance, we can use it by writing:
const div = document.querySelector('div')
for (let i = 1; i <= 100; i++) {
const p = document.createElement('p')
p.textContent = i
div.appendChild(p)
}
window.addEventListener('scroll', (e) => {
console.log(window.scrollY);
})
We still listen to the 'scroll'
event, but we get the window.scrollY
property instead of document.documentElement.scrollTop
.
Conclusion
There’re several ways we can use to get the scrollbar position with JavaScript.