Home >Web Front-end >JS Tutorial >How to Scroll to an Element Using JavaScript?

How to Scroll to an Element Using JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-10-21 19:17:03568browse

How to Scroll to an Element Using JavaScript?

How do I scroll to an element using JavaScript?

You can use the scrollIntoView() method to scroll to a specific element on a web page. This method is supported by all major browsers.

To use the scrollIntoView() method, simply pass the element you want to scroll to as an argument to the method. For example, the following code scrolls to the element with the ID "divFirst":

document.getElementById("divFirst").scrollIntoView();

The scrollIntoView() method can take an optional second argument that specifies how the element should be scrolled into view. The following values are accepted:

  • "auto": The element will be scrolled into view as much as possible without scrolling the page away from its current position.
  • "smooth": The element will be scrolled into view smoothly, with an animation effect.
  • "if-needed": The element will only be scrolled into view if it is not already visible.

For example, the following code scrolls to the element with the ID "divFirst" smoothly:

document.getElementById("divFirst").scrollIntoView({behavior: "smooth"});

You can also use the scrollIntoView() method to scroll to a specific offset within an element. To do this, pass an object with the following properties as the second argument to the method:

  • "block": The offset from the top of the element, in pixels.
  • "inline": The offset from the left of the element, in pixels.

For example, the following code scrolls to the element with the ID "divFirst" and offsets it by 100 pixels from the top and 50 pixels from the left:

document.getElementById("divFirst").scrollIntoView({block: 100, inline: 50});

The above is the detailed content of How to Scroll to an Element Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn