How to scroll to an element inside a div? How to scroll to an element inside a div? javascript javascript

How to scroll to an element inside a div?


You need to get the top offset of the element you'd like to scroll into view, relative to its parent (the scrolling div container):

var myElement = document.getElementById('element_within_div');var topPos = myElement.offsetTop;

The variable topPos is now set to the distance between the top of the scrolling div and the element you wish to have visible (in pixels).

Now we tell the div to scroll to that position using scrollTop:

document.getElementById('scrolling_div').scrollTop = topPos;

If you're using the prototype JS framework, you'd do the same thing like this:

var posArray = $('element_within_div').positionedOffset();$('scrolling_div').scrollTop = posArray[1];

Again, this will scroll the div so that the element you wish to see is exactly at the top (or if that's not possible, scrolled as far down as it can so it's visible).


You would have to find the position of the element in the DIV you want to scroll to, and set the scrollTop property.

divElem.scrollTop = 0;

Update:

Sample code to move up or down

  function move_up() {    document.getElementById('divElem').scrollTop += 10;  }  function move_down() {    document.getElementById('divElem').scrollTop -= 10;  }


Method 1 - Smooth scrolling to an element inside an element

var box = document.querySelector('.box'),    targetElm = document.querySelector('.boxChild'); // <-- Scroll to here within ".box"document.querySelector('button').addEventListener('click', function(){   scrollToElm( box, targetElm , 600 );   });/////////////function scrollToElm(container, elm, duration){  var pos = getRelativePos(elm);  scrollTo( container, pos.top , 2);  // duration in seconds}function getRelativePos(elm){  var pPos = elm.parentNode.getBoundingClientRect(), // parent pos      cPos = elm.getBoundingClientRect(), // target pos      pos = {};  pos.top    = cPos.top    - pPos.top + elm.parentNode.scrollTop,  pos.right  = cPos.right  - pPos.right,  pos.bottom = cPos.bottom - pPos.bottom,  pos.left   = cPos.left   - pPos.left;  return pos;}    function scrollTo(element, to, duration, onDone) {    var start = element.scrollTop,        change = to - start,        startTime = performance.now(),        val, now, elapsed, t;    function animateScroll(){        now = performance.now();        elapsed = (now - startTime)/1000;        t = (elapsed/duration);        element.scrollTop = start + change * easeInOutQuad(t);        if( t < 1 )            window.requestAnimationFrame(animateScroll);        else            onDone && onDone();    };    animateScroll();}function easeInOutQuad(t){ return t<.5 ? 2*t*t : -1+(4-2*t)*t };
.box{ width:80%; border:2px dashed; height:180px; overflow:auto; }.boxChild{   margin:600px 0 300px;   width: 40px;  height:40px;  background:green;}
<button>Scroll to element</button><div class='box'>  <div class='boxChild'></div></div>