We create an HTML div element with an id of “scroll-element” and select it using the querySelector() method. A paragraph element is defined within this division element with a height and width greater than that of the div element for the scroll bars to be visible. Another div element is created with the “output” class to show the scroll position of the first division element. Use the addEventListener() method to attach an event listener to the div element with an id of “scroll-element”. The event to be attached is the scroll event.
Update the inner content of the div element with the “output” class using the innerHTML property. The scrollTop property gets or sets the number of pixels that an element’s content is scrolled vertically whereas the scrollLeft property gets or sets the number of pixels that an element’s content is scrolled from its left edge. The innerHTML is repeatedly updated on scrolling through the HTML document.
Note: The scrollTop and scrollLeft properties may return an unrestricted double data type in certain situations so the Math.ceil() method is used to round up to the nearest integer.
Example: In this example, apart from the scroll event, there are two buttons created with classes “scroll-top-btn” and “scroll-left-btn” respectively. The first button on click increments the scrollTop property of the div element with an id of “scroll-element” by 25 and the second button on click increments the scrollLeft property of the division element by 25.