scrollBy()
In JavaScript, scrollBy()
is a function provided by the browser’s window
object. It scrolls the window content up, down, left, or right based on the specified parameters. The scrolling occurs relative to the current scroll position, meaning if the user has already scrolled 100 pixels down and scrollBy(0, 100)
is called, the new scroll position will be 200 pixels down the page.
Syntax
window.scrollBy(x-coordinate, y-coordinate);
Or, alternatively:
window.scrollBy(options);
x-coordinate
: The number of pixels to scroll horizontally. A positive number will scroll right and a negative number will scroll left.y-coordinate
: The number of pixels to scroll vertically. A positive number will scroll down and a negative number will scroll up.options
: An object that takes up to three properties:left
: The number of pixels to scroll horizontally.top
: The number of pixels to scroll vertically.behavior
: Determines the scrolling animation. This can either beinstant
,smooth
, orauto
.
Example 1
The following example uses the scrollBy()
function to scroll the window down by 200 pixels when a button is clicked:
// Get the button elementconst scrollButton = document.getElementById('scrollButton');// Scroll down by 200 pixels when the button is clickedscrollButton.addEventListener('click', function () {window.scrollBy(0, 200);});
Example 2
The following example scrolls the window 100 pixels to the left and 100 pixels up using negative values:
// Get the button elementconst scrollButton2 = document.getElementById('scrollButton2');// Scroll left by 100 pixels and up by 100 pixels when the button is clickedscrollButton2.addEventListener('click', function () {window.scrollBy(-100, -100);});
Example 3
The following example scrolls the window 200 pixels to the right, 150 pixels down, and uses smooth scrolling, implemented by the options
parameter:
// Get the button elementconst scrollButton3 = document.getElementById('scrollButton3');// Smoothly scroll right by 200 pixels and down by 150 pixels when the button is clickedwindow.scrollBy({top: 150,left: 200,behavior: 'smooth',});
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn JavaScript on Codecademy
- Career path
Front-End Engineer
Front-end engineers work closely with designers to make websites beautiful, functional, and fast.Includes 34 CoursesWith Professional CertificationBeginner Friendly115 hours - Free course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner Friendly15 hours