How to Scroll to an Element using JavaScript
š
December 4, 2022
šJavaScript
In this article, we will show you how to scroll to a specific element using JavaScript. Here we will discuss different ways to achieve this.
1. Using location hash
In this method, we will use the hash property of the location. Run the following command on button/link click.
location.hash = "elementID";
2. Using scrollIntoView method
The Element interfaceās scrollIntoView() method scrolls the elementās parent container such that the element on which scrollIntoView() is called is visible to the user.
document.getElementById("elementID").scrollIntoView();
3. Using scrollTo method
The scrollTo() method of the Element interface scrolls to a particular set of coordinates inside a given element.
var scrollElement = document.getElementById("elementID").offsetTop;
window.scrollTo({ top: scrollElement, behavior: 'smooth'});
I hope you find this article helpful.
Thank you for reading. Happy Coding..!!