Home >Web Front-end >JS Tutorial >How to 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:
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:
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!