I have an html and css slider where I'm using scroll-snap for manual scrolling and jQuery buttons for automatic scrolling. However, when using scroll-snap-type: x mandatory;, the jQuery scrollLeft animation becomes extremely laggy or the animation disappears. Where is this lag coming from? Is there a jQuery only solution?
Taking out the css scroll-snap fixes the problem, but the style is necessary to the slider.
HTML
<div class="container">
  <div class="box"></div>
  <div class="box"></div> 
  <div class="box"></div>
</div>
<button id="left">←</button>
<button id="right">→</button>
CSS
.container {
  max-width: 300px;
  display: flex;
  scroll-snap-type: x mandatory;
  overflow-x: auto;
}
.box {
  min-width: 100%;
  min-height: 250px;
  scroll-snap-align: center;
  scroll-snap-stop: normal;
}
.box:nth-child(1) {background: #f55;}
.box:nth-child(2) {background: #5f5;}
.box:nth-child(3) {background: #5ff;}
jQuery
$("#right, #left").click(function() {
  var dir = this.id=="right" ? '+=' : '-=' ;
  $(".container").stop().animate({scrollLeft: dir+'300'}, 300);
});
Here's a live example: https://codepen.io/tystrong/pen/rboLYz
I solved this issue by disabling the scroll-snap-type property during the scroll animation. Then in the animate() callback I just re-enable it.
Here's my simplified code:
$arrows.on("click", event => {
  $track.css("scroll-snap-type", "none");
  $track.stop().animate(
    { scrollLeft: left },
    500,
    () => $track.css("scroll-snap-type", "x mandatory")
  );
});
                        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