Skip to content
Related Articles

Related Articles

Improve Article

HTML | Window scrollBy() method

  • Last Updated : 30 Jul, 2019

The window.scrollBy() method is used to scroll the document by given number of pixels.

Syntax:

window.scrollBy( xcoordinate, ycoordinate );

or

window.scrollBy(options);

Parameters: This method accepts two parameters as mentioned above and described below:

  • x-coordinate: It is the horizontal pixel value which indicates how much you want to scroll the document (in terms of px).
  • y-coordinate: It is the vertical pixel value which indicates how much you want to scroll the document (in terms of px).

Note: You can find these options in options in ScrollToOptions dictionary.



Example 1: Scroll horizontally




<!DOCTYPE html>
<html>
      
<head>
    <title>
        HTML | DOM window scrollby() method
    </title>
      
    <style>
        body {
            width: 5000px;
        }
        a:focus {
            background-color: magenta;
        }
        button {
            position: fixed;
        }
    </style>
</head>
  
<body>
    <h1 style="color:green;"
        GeeksforGeeks 
    </h1>
  
    <h2>HTML DOM Window.scrollBy() method</h2>
  
    <button onclick="scrollby()">
        Scroll horizontally!
    </button>
      
    <br><br>
  
    <script>
        function scrollby() {
            window.scrollBy(100, 0);
        }
    </script>
</body>
  
</html>

Output:

Example 2: Using options




<!DOCTYPE html>
<html>
  
<head>
    <title>
        HTML | DOM Window scrollBy() method
    </title>
      
    <style>
        body {
            width: 5000px;
            height:5000px;
        }
        a:focus {
            background-color: magenta;
        }
        button {
            position: fixed;
        }
    </style>
</head>
  
<body>
    <h1 style="color:green;"
        GeeksForGeeks 
    </h1>
  
    <h2>HTML DOM Window.scrollBy() method</h2>
  
    <div>
        <button onclick="scrollWin(0, 50)">
            Scroll down
        </button>
          
        <br><br>
          
        <button onclick="scrollWin(0, -50)">
            Scroll up
        </button>
          
        <br><br>
          
        <button onclick="scrollWin(50, 0)">
            Scroll right
        </button>
          
        <br><br>
          
        <button onclick="scrollWin(-50, 0)">
            Scroll left
        </button>
    </div>
  
    <script>
        function scrollWin(x, y) {
            window.scrollBy(x, y);
        }
    </script>
</body>
  
</html>                    

Output:

Supported Browsers: The browser supported by HTML DOM Window scrollBy() method are listed below:

  • Google Chrome 45
  • Firefox
  • Opera 32

Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :