Sam Assoum
Sam Assoum

Reputation: 447

Use jQuery to scroll div horizontally back and forth on loop

I couldn't find any posts about this Googling suprisingly, I'm making the assumption (probably foolish assumption) that what I need has a simple solution though.

I have a div with child element that has a width wider than the viewport (on mobile), I have overflow-x: scroll on the child element so the horizontal scroll bar appears. I'd like to use jquery to animate the horizontal scroll position of this element so it slowly scrolls from left to right and back again once it reaches the end, ideally looping infinitely.

I kind of don't want to post this because I don't have any jQuery written to contribute, but I'm not sure where to start.

HTML:

<div class="parent">
  <div class="wide_content"></div>
</div> 

CSS:

.wide_content {
    width: 1200px;
    overflow-x: scroll;                            
    -webkit-overflow-scrolling: touch;
}

Upvotes: 0

Views: 2128

Answers (1)

Ugo T.
Ugo T.

Reputation: 1078

If you want an infinite right and left scrolling motion you have can use, for example, the JQuery animate() function and an infinite loop :

var scroll = function(width) {
  $('html, body').animate({
    scrollLeft: width,
  }, 2000);
};

var loopForever = function(delay, callback) {
  var loop = function() {
    callback();
    setTimeout(loop, delay);
  };
  loop();
};

loopForever(1000, function() {
  scroll($('.wide_content').width());
  scroll(0);
});
.wide_content {
  width: 1200px;
  overflow-x: scroll;
  -webkit-overflow-scrolling: touch;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent">
  <div class="wide_content"></div>
</div>

Upvotes: 2

Related Questions