When a page loads with the div below I want the page to start auto scrolling and keep looping through the content over and over again. To see an example of what I am trying to achieve go here
<div id="contentwrapper">
<div class="post">some content</div>
<div class="post">some content</div>
<div class="post">some content</div>
<div class="post">some content</div>
<div class="post">some content</div>
<div class="post">some content</div>
</div>
Any help will be greatly appreciated as I have tried almost everything with no success.
You can change the scroll position of an element by setting the scrollTop property. To update it continuously, you could try:
var scrollDistancePerSecond = 50; // Scroll 50px every second.
var scrollDistancePerAnimationFrame = Math.ceil(scrollDistancePerSecond / 60); // Animate at 60 fps.
var wrapper = document.getElementById('contentwrapper');
autoScroll(wrapper);
function autoScroll(element){
if (element.scrollTop < element.scrollHeight)
window.requestAnimationFrame(autoScroll.bind(null,element));
element.scrollTop += scrollDistancePerAnimationFrame;
}
Live example here.
As for the continuous loop, you could wrap the .post elements in an inner wrapper (e.g., a <div id="inner-wrap">. Then you could duplicate the content by appending a clone of the inner-wrapped elements inside the outer wrapper.
var innerWrap = document.getElementById('inner-wrap');
var clone = document.createElement('div');
clone.innerHTML = innerWrap.innerHTML;
wrapper.append(clone);
Then, inside your animation function, you can check whether the wrapper's scrollTop has reached innerWrap.scrollHeight. If it has, you can jump back to the top! It'll take some fine-tuning to get a seamless effect.
The linked page does not use scrollTop, but animates the y component of the CSS transform translate3d on the wrapper <div>. You might get more performant results using CSS transitions or animations over JavaScript. Here is an example in pure CSS3.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With