Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto scroll a horizontal div

Tags:

javascript

I thought this would be fairly easy but I'm stuck.

My code is executing and ignoring the setTimeout.

I am getting the scroll width of my element, then saying while i is less than the width (flavoursScrollWidth), move the horizontal scroll 1px along every second.

That isn't what is happening though, it just executes each pixel movement almost instantly.

I also tried taking the code out of the load event and taking the setTimeout out of the while loop. Then creating a function containing the while loop, and calling the function in a setInterval. Didn't help.

const flavoursContainer = document.getElementById("flavoursContainer")
const flavoursScrollWidth = flavoursContainer.scrollWidth

window.addEventListener("load", () => {
  let i = 0
  while (i < flavoursScrollWidth) {
    setTimeout(flavoursContainer.scrollTo(i, 0), 1000)
    console.log(i)
    i++;
  }
})
.container {
  width:300px;
  overflow-x:scroll;
  white-space: nowrap;
}
<div class="container" id="flavoursContainer">
    This is a really long sentence to demo my code, it's just going on and on. Still going. I should have used some default placeholder text but I've started now so I'll keep going.
</div>
like image 666
GoldenGonaz Avatar asked Apr 22 '18 17:04

GoldenGonaz


1 Answers

I would suggest using setInterval rather than setTimeout and just checking if the container is scrolled to the end. I also found that if you scroll faster, like every 15ms, you get a smoother user experience.

const flavoursContainer = document.getElementById('flavoursContainer');
const flavoursScrollWidth = flavoursContainer.scrollWidth;

window.addEventListener('load', () => {
  self.setInterval(() => {
    if (flavoursContainer.scrollLeft !== flavoursScrollWidth) {
      flavoursContainer.scrollTo(flavoursContainer.scrollLeft + 1, 0);
    }
  }, 15);
});
.container {
  width: 300px;
  overflow-x: scroll;
  white-space: nowrap;
  background-color: #fff;
}
<div class="container" id="flavoursContainer">
  This is a really long sentence to demo my code, it's just going on and on. Still going. I should have used some default placeholder text but I've started now so I'll keep going.
</div>
like image 168
jdgregson Avatar answered Oct 01 '22 13:10

jdgregson