Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference Between scrollY and scrollTop

Tags:

javascript

What is the difference between scrollY and scrollTop
What is difference between scrollX and scrollLeft

window.addEventListener('scroll', ()=>{
    console.log(document.querySelector('html[lang="en"]').scrollTop) //Same Result
    console.log(window.scrollY)
})
like image 642
Khaled Zain Avatar asked Jul 27 '26 09:07

Khaled Zain


2 Answers

scrollY/X - (based on window) The read-only scrollY property of the Window interface returns the number of pixels that the document is currently scrolled vertically. You can get the number of pixels the document is scrolled horizontally from the scrollX property.

scrollTop/Left - (based on element) The scrollLeft and scrollTop properties return the number of pixels that the element’s content is scrolled from its left and top edges.

The first uses the window object while the later uses the DOM element.

Mozilla -> NOTE: When scrollTop is used on the root element (the <html> element), the scrollY of the window is returned. This is a special case of scrollTop.

So in your instance, it seems there is no difference when used on the root html element.

like image 97
dale landry Avatar answered Jul 28 '26 21:07

dale landry


ScrollTop is basically can be get and set, where as scrollY of window's only can be get. ScrollTop is Element's property where as ScrollY is of Window's property.

like image 35
Asutosh Avatar answered Jul 28 '26 22:07

Asutosh