Scrolling to a element inside a scrollable DIV with pure Javascript

You need to read the offsetTop property of the div you need to scroll to and then set that offset to the scrollTop property of the container div. Bind this function the event you want to :

function scrollToElementD(){
    var topPos = document.getElementById('inner-element').offsetTop;
    document.getElementById('container').scrollTop = topPos-10;
}
div {
    height: 200px;
    width: 100px;
    border: 1px solid black;
    overflow: auto;
}

p {
    height: 80px;
    background: blue;
}
#inner-element {
    background: red;
}
<div id="container"><p>A</p><p>B</p><p>C</p><p id="inner-element">D</p><p>E</p><p>F</p></div>
<button onclick="scrollToElementD()">SCROLL TO D</button>
function scrollToElementD(){
  var topPos = document.getElementById('inner-element').offsetTop;
  document.getElementById('container').scrollTop = topPos-10;
}

Fiddle : http://jsfiddle.net/p3kar5bb/322/ (courtesy @rofrischmann)

Leave a Comment