scroll to element using javascript

How to Scroll to Element with JavaScript

JavaScript is a popular front end language for web developers. It offers tons of features & functions. Sometimes our web pages may be long and have many DOM elements. It is easier for users to navigate long web pages if you add a scroll to element functionality that allows users to directly go to the element they wish to view, instead of manually scrolling down to it. In this article, we will learn how to scroll to element using JavaScript.


How to Scroll to Element with JavaScript

Here are the steps to scroll to element with JavaScript. Let us say you have the following HTML page with 2 divs and 1 button.

<html>
   <body>
    <button id="click">Click me</button>
    <div id="div1" style="height: 1000px; width 100px">
        Test
    </div>
    <br/>
    <div id="div2" style="height: 1000px; width 100px">
        Test 2
    </div>

  </body>
</html>

Each of the above divs is 1000px in height making it inconvenient for users to manually scroll down to the second div. To overcome this problem, we will add a functionality to our button such that when you click it, users will directly scroll down to the 2nd div.

For this purpose, you can use scrollIntoView function as shown below.

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

We will create a click handler for our button and add the above line in it.

<button id="click" onclick='myfunc'>Click me</button>

We will define the above mentioned myfunc as shown.

<script>
function myfunc() {
  document.getElementById("div2").scrollIntoView();
}
</script>

Here is the entire code.

<html>
   <body>
    <button id="click" onclick='myfunc'>Click me</button>
    <div id="div1" style="height: 1000px; width 100px">
        Test
    </div>
    <br/>
    <div id="div2" style="height: 1000px; width 100px">
        Test 2
    </div>

<script>
  function myfunc() {
    document.getElementById("div2").scrollIntoView();
  }
</script>
  </body>
</html>

Now when users click the button, myfunc() function is called which scrolls down to div2 div.

In this article, we have learnt how to implement scroll to element using plain JavaScript. This is useful if your web page is long with many DOM elements, or if your DOM elements are dynamically loaded using infinite scroll plugins. You can also use other JS libraries such as jQuery to implement scroll to element feature. This simplifies website navigation and makes them more interactive. You can not only use this to scroll down to element, but also to scroll back to top.

Also read:

How to Scroll to Element using jQuery
How to Add Delay in JavaScript Loop
How to Use Dynamic Variable Names in JavaScript
How to Get Difference Between Two Arrays
How to Compare Dictionary in Python

Leave a Reply

Your email address will not be published. Required fields are marked *