scrollBy()

PhillipAlter's avatar
Published Feb 25, 2025
Contribute to Docs

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 be instant, smooth, or auto.

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 element
const scrollButton = document.getElementById('scrollButton');
// Scroll down by 200 pixels when the button is clicked
scrollButton.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 element
const scrollButton2 = document.getElementById('scrollButton2');
// Scroll left by 100 pixels and up by 100 pixels when the button is clicked
scrollButton2.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 element
const scrollButton3 = document.getElementById('scrollButton3');
// Smoothly scroll right by 200 pixels and down by 150 pixels when the button is clicked
window.scrollBy({
top: 150,
left: 200,
behavior: 'smooth',
});

All contributors

Contribute to Docs

Learn JavaScript on Codecademy