JSFiddle - React, Tailwind, and code Playground
by glee
HTML
<div class = "container">
<div class = "content">
<img width = "250px" src = "https://fbcdn-sphotos-f-a.akamaihd.net/hphotos-ak-ash4/217069_10151149856432044_523490170_n.jpg" alt = ""/><img width = "250px" src = "https://fbcdn-sphotos-e-a.akamaihd.net/hphotos-ak-ash4/305274_10151148068047044_1390975783_n.jpg" alt = ""/><img width = "250px" src = "https://fbcdn-sphotos-d-a.akamaihd.net/hphotos-ak-prn1/562994_10151146774587044_1253382411_n.jpg" alt = ""/><img width = "250px" src = "https://fbcdn-sphotos-f-a.akamaihd.net/hphotos-ak-prn1/523562_10151145448562044_845995820_n.jpg" alt = ""/></div>
</div>
<div class = "pagination">
<span>1</span>
<span>2</span>
<span>3</span>
<span>4</span>
</div>
CSS
.container {
width: 250px;
height: 332px;
border: 2px solid rgb(0, 162, 232);
overflow: hidden;
position: relative;
}
.content {
position: absolute;
white-space: nowrap;
}
.content img {
display: inline-block;
}
.pagination {
background-color: rgb(0, 162, 232);
}
.pagination span {
color: white;
cursor: pointer;
}
JavaScript
var cont, lft;
function anim() {
var curleft = cont.offset().left;
cont.animate({left: 0}, Math.floor((curleft - 250) / (lft - 250) * 7000), function() { //animate for a total of 7000ms = 7s
cont.animate({left: lft}, 500, function() {//get it back to the right
anim(); //and again!
});
});
}
$(document).ready(function() {
cont = $(".content");
lft = -(cont.width()) + 250; //calculate appropriate initial left value
cont.css({left: lft});
anim(); //animatie
});
$(".pagination span").click(function() { //when a pagination span is clicked
var cur = $(this); //get the span that was clicked
var idx = cur.index(); //get its index in .pagination (0-based index)
cont.stop().animate({left: lft + 250 * (3 - idx)}, function() { //animate to proper left position depending on the clicked index
setTimeout(anim, 1000); //wait 1s, then get back to normal animation
});
});
/*how the pagination works:
After we get the index, we must caclulate the appropriate left value. Intuitively, we should add 250 (the width of each frame) when you're requesting second slide, add 500 when you're requesting third, 750 when you're requesting fourth. But since our animation goes right-to-left, we must do the opposite -- add 250 when you're requesting third, 500 when you're requesting second, 750 when you're requesting first. Thus our formula for left is lft + 250 * (3 - idx).*/