JSFiddle - React, Tailwind, and code Playground
HTML
<div class="slider-wrap">
<div class="slide-wrap">
<div class="slider-slide-wrap shown">1</div>
<div class="slider-slide-wrap">2</div>
<div class="slider-slide-wrap">3</div>
</div>
</div>
<div id="slider-left" class="slider-nav"></div>
<div id="slider-right" class="slider-nav"></div>
CSS
.slider-wrap {
position: relative;
width: 100%;
height: 230px;
overflow-y:hidden;
overflow-x:scroll;
margin-top: 20px;
}
.slider-nav {
position: absolute;
margin-top: -125px;
width: 30px;
height: 30px;
background-color: rgba(0, 0, 0, 0.5);
-webkit-border-radius: 15px;
-moz-border-radius: 15px;
border-radius: 15px;
cursor: pointer;
z-index: 4;
}
#slider-left {
left: 20px;
}
#slider-right {
right: 20px;
}
.slide-wrap {
position: relative;
height: 200px;
top: 0;
left: 0;
}
.slider-slide-wrap {
position: absolute;
width: 680px;
height: 100%;
background-color: pink;
}
.slider-slide-wrap:nth-child(even) {
background-color: red;
}
JavaScript
$(document).ready(function () {
var n = $(".slider-slide-wrap").length,
width = 480,
newwidth = width * n;
$('.slide-wrap').css({
'width': newwidth
});
$(".slider-slide-wrap").each(function (i) {
var thiswid = 680;
$(this).css({
'left': thiswid * i
});
});
/*on scroll move the indicator 'shown' class to the
most visible slide on viewport
*/
$('.slider-wrap').scroll(function () {
var scrollLeft = $(this).scrollLeft();
$(".slider-slide-wrap").each(function (i) {
var posLeft = $(this).position().left
var w = $(this).width();
if (scrollLeft >= posLeft && scrollLeft < posLeft + w) {
$(this).addClass('shown').siblings().removeClass('shown');
}
});
});
/* on left button click scroll to the previous sibling of the current visible slide */
$('#slider-left').click(function () {
var $prev = $('.slide-wrap .shown').prev();
if ($prev.length) {
$('.slider-wrap').animate({
scrollLeft: $prev.position().left
}, 'slow');
}
});
/* on right button click scroll to the next sibling of the current visible slide */
$('#slider-right').click(function () {
var $next = $('.slide-wrap .shown').next();
if ($next.length) {
$('.slider-wrap').animate({
scrollLeft: $next.position().left
}, 'slow');
}
});
});