Clue Mediator

Scroll to a specific element using JavaScript

πŸ“…January 1, 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.

Checkout more articles on JavaScript

  • string-using-javascript" title="How to remove HTML tags from a string using JavaScript">How to remove HTML tags from a string using JavaScript
  • Remove a property from an object in JavaScript
  • array-into-chunks-in-javascript" title="Split an array into chunks in JavaScript">Split an array into chunks in JavaScript
  • url-in-a-new-tab-using-javascript" title="How to open an URL in a new tab using JavaScript">How to open an URL in a new tab using JavaScript

Ways to scroll to a specific element using JavaScript

  1. location hash">Using location hash
  2. Using scrollIntoView method
  3. Using scrollTo method

1. Using location hash

In this method, we will use the API/Location/hash" title="hash">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..!! πŸ™‚