0

HTML:

<div id="parent">
    <div class="myDiv"></div>
    <div class="myDiv"></div>
    <div class="myDiv mySelectedDiv"></div>
    <div class="myDiv"></div>
</div>

I append the mySelectedDiv class to the divs, one at a time, dynamically. I want the scrollbar to position at that selected div. Any suggestions?

I've tried the code below to move the scrollbar up and down at the position of the selected div. But its not much accurate when the divs' height change, which they do in my case.

element.scrollBy({
      top: 100,
      behavior: "smooth"
    })
Ahmet Ömer
  • 614
  • 1
  • 10
  • 18
  • _“when the divs' height change, which they do in my case”_ - when/how? And what do you want to happen in that case - should the scrolling automatically adjust itself to the “new” position, or what? – misorude Oct 19 '18 at 08:47

2 Answers2

2

You should be able to do it by using window.scrollTo() after you get the top Y coordinate of the element, relative to the window or a container or whichever is good for you.

That 2nd part probably has MANY answers on stackoverflow :) https://stackoverflow.com/search?q=get+element+top+position


Edit: If you don't care about old browsers, you can also try this new API: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView

Edit 2: As was pointed out by @mplungjan in a comment, this is actually quite supported across all browsers, even old ones such as IE6. At the least, the basic syntax. However, it is considered an experimental technology which is not standardized, so might want to test it well.

nomæd
  • 421
  • 5
  • 13
0

This is the solution that worked for me:

let parent = document.getElementsByClassName('parent-div')[0];
let selectedDiv = document.querySelector('.div-selected').getBoundingClientRect().top;

parent.scrollBy({
  top: selectedDiv - 100,
  behavior: "smooth"
})

It helps to calculate the position with a -100px so that the scrollbar centers the selected div.

Ahmet Ömer
  • 614
  • 1
  • 10
  • 18