JavaScript scrollIntoView() method

This tutorial will help you to understand the Java Script scrollIntoView() method.

JavaScript scrollIntoView() method

JavaScript scrollIntoView() method

In this section we will discuss about JavaScript scrollIntoView()method. Scroll bar is almost supported by all browser. Scroll bar is used to scroll the element into the visible area of document. By default the scroll is aligned to the top side. But you can set the alignment with the first parameter of the scrollIntoView() method JavaScript scrollIntoView() method.

Syntax :

object.scrollIntoView([allignToTop])

Where allignToTop is a boolean value which is optional. You can set it to true or false.

Parameter: Boolean value that indicated the type of align.

  • true : The element will be align to the top of the scrollable area. true is the default value,
  • false : The element will be align to the bottom of the scrollable area.

The method doesn't return any value.

Example : This example will illustrate the scrollIntoView() method. In this example we have created a scrollable area in which some text is written, when user click on the button then the text is displayed according to the button clicked. If first button is clicked then the top of the text is displayed because true is default value and if the second button is clicked then the bottom of the text is displayed.

<head>
<script type="text/javascript">
function ScrollRed (align) {
var redText = document.getElementById ("scrollText");
redText.scrollIntoView (align);
}
</script>
</head>
<body>
<div style="width:200px; height:200px; overflow:auto; background-color:#E0d0b0;">
<div style="height:200px;"></div>
<span id="scrollText" style="color:black">The Information technology industry in India has gained a brand identity as a knowledge economy due to its IT and ITES sector. The IT?ITES industry has two major components: IT Services and business process outsourcing (BPO). The growth in the service sector in India has been led by the IT?ITES sector, contributing substantially to increase in GDP, employment, and exports. 
.</span>
<div style="height:200px;"></div>
</div>
<br /><br/>
<button onclick="ScrollRed (true);">Click to view!</button>
<br />
<button onclick="ScrollRed (false);">Click to view!</button>
</body>

Output : When you click on the first button "Click view" then it will display the text at the top of the scrollable area because true is the default one.

And, when you click on the second button i.e."Click view" than the text in the bottom will displayed.

As you can see the difference between the two output.

Download Source Code