JSFiddle - React, Tailwind, and code Playground
by vencs
HTML
<div id="container">
<div id="block1" class="innerUnit"></div>
<div id="block2" class="innerUnit"></div>
<div id="block3" class="innerUnit"></div>
<div id="block4" class="innerUnit"></div>
<div id="block5" class="innerUnit"></div>
<div id="block6" class="innerUnit"></div>
<div id="block7" class="innerUnit"></div>
</div>
<div id="preBtn" class="btn">Previous</div>
<div id="nextBtn" class="btn">Next</div>
CSS
#container {
font-size:0;
border:black 3px solid;
width:400px;
height:60px;
overflow: hidden;
white-space: nowrap;
}
.innerUnit {
height:100%;
display:inline-block;
}
.btn {
margin-top:2px;
cursor:pointer;
border:black 1px solid;
background-color:#efefef;
display:inline-block;
}
#block1 {
width:140px;
background-color:red;
}
#block2 {
width:200px;
background-color:orange;
}
#block3 {
width:170px;
background-color:yellow;
}
#block4 {
width:160px;
background-color:green;
}
#block5 {
width:100px;
background-color:blue;
}
#block6 {
width:140px;
background-color:#6600FF;
}
#block7 {
width:260px;
background-color:purple;
}
JavaScript
function $(pattern) {
return document.querySelector(pattern);
}
var longPressAct;
function moveElements(container, direction) {
var childElements = container.children,
maxScrollLeft = container.scrollWidth - container.clientWidth,
currentScrollLeft = container.scrollLeft,
moveRight = direction === 'R';
//boarder line check
if (moveRight && currentScrollLeft === maxScrollLeft) return;
else if (!moveRight && currentScrollLeft === 0) return;
var accumulatedWidth = 0,
widthArray = [],
currentFrontTabIndex = 0;
for (var i = 0, max = childElements.length; i < max; i++) {
if(childElements[i].style.display==='none') continue;
accumulatedWidth += childElements[i].offsetWidth;
widthArray.push(accumulatedWidth);
if (currentScrollLeft >= accumulatedWidth) {
currentFrontTabIndex++;
}
}
var moveScale = 12;
var scrollRange, moveFunc, remainder;
if (moveRight) {
scrollRange = widthArray[currentFrontTabIndex] - (currentFrontTabIndex > 0 ? widthArray[currentFrontTabIndex-1] : 0);
remainder = scrollRange % moveScale;
moveFunc = function () {
if (scrollRange >= moveScale) {
scrollRange -= moveScale;
container.scrollLeft += moveScale;
requestAnimationFrame(moveFunc);
} else {
scrollRange -= remainder;
container.scrollLeft += remainder;
}
};
} else {
scrollRange = currentScrollLeft - (currentFrontTabIndex >= 2 ? widthArray[currentFrontTabIndex-2] : 0);
remainder = scrollRange % moveScale;
moveFunc = function () {
if(remainder!==0){
scrollRange -= remainder;
container.scrollLeft -= remainder;
remainder=0; //set remainder to zero to make the calculation easier.
requestAnimationFrame(moveFunc);
...