Search code examples
javascriptscrollscrollto

auto continuous horizontal scroll to keep consecutively identified elements in center of view


Project: https://3milychu.github.io/criminal/

I have about 6000 divs in a horizontal scrolling parent container.

Each second, I scroll to the next div using the scrollTo method using behavior: 'smooth'

This results in an abrupt motion, stopping at each div before continuing to the next.

Is there a way to make the parent container scroll continuously at a consistent speed without stopping while keeping the target div at each second in the center of the viewport?

function sonify(data){
    var counter = -1;
    setInterval(function() {
        if(counter<6172){
            counter++
            container = document.querySelector('#track1')
            person = document.querySelector('#person'+counter)
            hover(person)
            target=person.offsetLeft - window.innerWidth/2;
            container.scrollTo({
              left: target,
              behavior: 'smooth'
            });
            playVerdict(data,counter)
            playPriors(data, counter)
            playFelonies(data,counter)
            playFemale(data,counter)
            }
    },808)
}

Solution

  • For something like that, your best bet is to roll your own with requestAnimationFrame and manually setting the container offset each frame. Basically think of a very simple game engine loop. Since it looks like you're syncing with audio, you need high precision, and css transitions can lag and probably will desync at some point.