JavaScript - scrollTo() method

revision:


Category : document

The scrollTo() method scrolls the document to specified coordinates. For the scrollTo() method to work, the document must be larger than the screen, and the scrollbar must be visible.

Syntax :

        window.scrollTo(x, y)
   
        scrollTo(x, y)
    

Parameters

x: required ; the coordinate to scroll to (horizontally), in pixels.

y: required ; the coordinate to scroll to (vertically), in pixels.

Examples


    

Category : element

The scrollTo() method of the Element interface scrolls to a particular set of coordinates inside a given element.

Syntax :

        scrollTo(x-coord, y-coord)
        scrollTo(options)
   

Parameters:

x-coord : the pixel along the horizontal axis of the element that you want displayed in the upper left.

y-coord : the pixel along the vertical axis of the element that you want displayed in the upper left.

options : A dictionary containing the following parameters:

top : specifies the number of pixels along the Y axis to scroll the window or element.
left : specifies the number of pixels along the X axis to scroll the window or element.
behavior : determines whether scrolling is instant or animates smoothly. This option is a string which must take one of the following values:

smooth: scrolling should animate smoothly.
instant: scrolling should happen instantly in a single jump.
auto : scroll behavior is determined by the computed value of scroll-behavior.

Examples

        element.scrollTo(0, 1000);
        element.scrollTo({
            top: 100,
            left: 100,
            behavior: "smooth",
        });

     

Practical examples

example: scroll to the top of the page and to the bottom of the page.

code
code:
                    <div>
                        <button id="seven" onclick="scrollToTop()">to the top</button><br>
                        <button id="seven" onclick="scrollToBottom()">to the bottom</button>
                    </div>
                    <script>
                        const scrollToTop = () =>{
                            window.scrollTo({ top: 0, left: 0, behavior: "smooth" });
                        };
            
                        const scrollToBottom = () => {
                            window.scrollTo({
                                top: document.documentElement.offsetHeight,
                                left: 0,
                                behavior: "smooth",
                            });
                            };
                    </script>