My HTML and CSS slider utilizes the scroll-snap
feature for manual scrolling along with jQuery buttons for automated scrolling. However, I have encountered an issue where using scroll-snap-type: x mandatory;
causes severe lag in the jQuery scrollLeft
animation or makes the animation disappear altogether. What could be causing this lag? Is there a potential solution using only jQuery?
Removing the CSS scroll-snap resolves the problem, but it is essential to maintain the slider's style.
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);
});
Feel free to explore a live example at: https://codepen.io/tystrong/pen/rboLYz