Element scrollIntoView() Method - Javascript DOM

Javascript examples for DOM:Element scrollIntoView

Description

The scrollIntoView() method scrolls the element into the visible area.

Parameters

Parameter TypeDescription
alignTo Boolean Optional.

alignTo value:

  • true - the top is aligned to the top of the visible area of the scrollable ancestor
  • false - the bottom is aligned to the bottom of the visible area of the scrollable ancestor.

If omitted, it will scroll to the top of the element.

Return Value:

No return value

Scroll the element with id="content" into the visible area of the browser window:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {//  w  w w  . j a  v  a  2  s  .  com
    height: 250px;
    width: 250px;
    overflow: auto;
    background: green;
}

#content {
    margin:500px;
    height: 800px;
    width: 2000px;
    background-color: coral;
    position: relative;
}
</style>
</head>
<body>

<button onclick="scrollToTop()">Scroll to the top of the element</button>
<button onclick="scrollToBottom()">Scroll to the bottom of the element</button>

<div id="myDIV">
  <div id="content">
    <div style="position:absolute;top:0;">Some text at the top</div>
    <div style="position:absolute;bottom:0">Some text at the bottom</div>
  </div>
</div>

<script>
var elmnt = document.getElementById("content");

function scrollToTop() {
    elmnt.scrollIntoView(true); // Top
}

function scrollToBottom() {
    elmnt.scrollIntoView(false); // Bottom
}
</script>

</body>
</html>

Related Tutorials