The following code shows an example of the scrollIntoView() method in JavaScript.

Programmingempire

Demonstrating Example of the scrollIntoView() Method in JavaScript

The following HTML code demonstrates the use of the scrollView() method. As can be seen in the code, there is an unordered list containing several items. Further, one of the list items is assigned an id with the value “i1”. Also, there is a button. When the user clicks on the button, the function f1() executes. At first, the list item is retrieved using the getElementById() method. After that, the scrollIntoView() method is called in order to bring that list item in the visible area of the browser.

<html>
<head>
  <title>scrollIntoView Method Demo</title>
  <script>
     
     function f1()
     {
	var x1=document.getElementById("i1");
        x1.scrollIntoView();
     }
  </script>
  <style>
    .fav{background: black;}
    .c1{
       border: 4px solid #33ff99;
       border-radius: 10px;
       background-color: #5566aa;
       color: #aaffff;
       font-size: 35px;
       text-align: left;
       margin:15px;
       padding: 30px;
      }
    .a1{
		margin: 50px;
	}
    .c2{
       background-color: #ddeeff;
       color: #ff5566;
       font-size: 25px;
       text-align: left;
       margin:40px;
       padding: 5px;
       width: 800px;
      }
  </style>
</head>
<body>
  <div id="d1" class="c2"><br/><br/>
     Example of scrollIntoView() Method<br/>
     <button id="b1" onclick="f1()">Show Favourite</button><br/>
     List of Countries...
     <br/>
	<ul class="c1">
		<li>Algeria</li>
		<li>Afganistan</li>
		<li>Australia</li>
		<li>Armenia</li>
		<li>Australia</li>
		<li>Bangladesh</li>
		<li>Botswana</li>
		<li>Brunei</li>
		<li>Canada</li>
		<li>China</li>
		<li>Denmark</li>
		<li>Estawini</li>
		<li>Finland</li>
		<li>France</li>
		<li>Germany</li>
		<li>Greenland</li>
		<li>Hungry</li>
		<li class="fav" id="i1">India</li>
		<li>Indonesia</li>
		<li>Italy</li>
		<li>Malaysia</li>
		<li>New Zealand</li>
		<li>Spain</li>
		<li>UK</li>
		<li>USA</li>
	</ul>
     <br/>
 </div>
</body>
</html>

Output

The Output of the Example of the scrollView() Method in JavaScript
The Output of the Example of the scrollView() Method in JavaScript

Further Reading

Evolution of JavaScript from ES1 to ES2020

Introduction to HTML DOM Methods in JavaScript

JavaScript Practice Exercise

programmingempire