Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS 'snap-scroll' interfering with jQuery '.animate scrollLeft'

Tags:

html

jquery

css

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">&larr;</button>
<button id="right">&rarr;</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

like image 767
Ty Strong Avatar asked Apr 25 '19 18:04

Ty Strong


1 Answers

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")
  );
});
like image 171
Brent Avatar answered Oct 05 '22 09:10

Brent