Method to scroll a window to the position in JavaScript

The scrollTo method scrolls the window to the specified position. The first parameter it takes is the horizontal position, and the second parameter is the vertical position. Let's scroll the window to a given position:

window.scrollTo(100, 200);

The method has an alternative syntax in which an object is passed as a parameter. The top key of this object specifies the horizontal position, the left key specifies the vertical position, and the behavior key specifies the scroll type. The type can be 'auto' or 'smooth'. With the last one, scrolling will be smooth.

element.scrollTo({ top: 100, left: 100, behavior: 'smooth' });

On button click, scroll the window to 300px position from the top.

On button click, smoothly scroll the window to the very top.

On button click, smoothly scroll the window to the very bottom.

enru