JSFiddle - React, Tailwind, and code Playground
HTML
<div id="everything">
<div id="container">
<div id="one">1</div>
<div id="two">2</div>
<div id="three">3</div>
<div id="four">4</div>
</div>
</div>
CSS
#everything {
border:1px solid black;
width:360px; height:120px;
position:relative; overflow:hidden;
}
#container {
background:#eef; width:480px;
position:absolute; top:0; left:0;
}
#container div {
float:left;
margin:10px;
background:#efe;
width:100px; height:100px;
}
JavaScript
var TRACK = (function () {
var p = document.createElement('p');
document.body.appendChild(p);
return function (str) {
p.innerHTML = str;
}
}());
var fade_timer,
going_left = true,
container = document.getElementById('container'),
one = document.getElementById('one'),
four = document.getElementById('four'),
set_opacity = function (elem, o) {
elem.style.opacity = o;
elem.style.filter = 'alpha(opacity=' + o * 100 + ')';
},
swap = function (fade_in, fade_out, end_left) {
var start_time = +new Date(), total_time = 750, end_time = start_time + total_time,
start_left = parseFloat(container.style.left) || 0, total_left = end_left - start_left,
in_start_o = parseFloat(fade_in.style.opacity) || 0, in_total_o = 1 - in_start_o,
out_start_o = parseFloat(fade_out.style.opacity) || 1, out_total_o = -out_start_o;
fade_timer = setInterval(function () {
var percent = +new Date(),
current_time = percent > end_time ? 1 : (percent - start_time) / total_time;
percent = (1 - Math.cos(current_time * Math.PI)) / 2;
set_opacity(fade_in, in_start_o + percent * in_total_o);
set_opacity(fade_out, out_start_o + percent * out_total_o);
container.style.left = (start_left + percent * total_left) + 'px';
if (current_time === 1) {
clearInterval(fade_timer);
}
}, 40);
};
document.getElementById('everything').onclick = function () {
clearInterval(fade_timer);
if (going_left) {
going_left = false;
swap(four, one, -120);
} else {
going_left = true;
swap(one, four, 0);
}
};