Scroll the element with id="content" into the visible area of the browser window:
Click the button to scroll to the top of the element with id="content".
<!DOCTYPE html> <html> <head> <style> #myDIV {//www. j ava 2 s . c om height: 250px; width: 250px; overflow: auto; background: green; } #content { margin:500px; height: 800px; width: 2000px; background-color: coral; } </style> </head> <body> <button onclick="myFunction()">Scroll</button> <div id="myDIV"> <div id="content"> Some text inside an element. </div> </div> <script> function myFunction() { var elmnt = document.getElementById("content"); elmnt.scrollIntoView(); } </script> </body> </html>
The scrollIntoView()
method scrolls the specified element into the visible area of the browser window.
element.scrollIntoView(alignTo);
Parameter | Type | Description |
---|---|---|
alignTo | Boolean | Optional. A boolean value that indicates the type of the align |
true - the top of the element will be aligned to the top of the visible area of the scrollable ancestor
false - the bottom of the element will be aligned to the bottom of the visible area of the scrollable ancestor.
If omitted, it will scroll to the top of the element.
The scrollIntoView()
method has No return value.