JSFiddle - React, Tailwind, and code Playground
by shchukin
HTML
<div class="some-layout">
<nav>
<ul>
<li><b>Lorem</b></li>
<li><b>ipsum dolor sit amet</b></li>
<li><b>consectetur adipiscing</b></li>
<li><b>elit</b></li>
<li><b>magna a tellus</b></li>
<li><b>sagittis</b></li>
<li><b>pellentesque non sit amet quam</b></li>
<li><b>gravida in faucibus vel</b></li>
<li><b>dignissim eget</b></li>
<li><b>eros quam</b></li>
</ul>
</nav>
<i class="next"></i>
<i class="prev"></i>
</div>
CSS
.some-layout {
width: 90%; /*unknown width*/
margin: 40px auto;
position: relative;
background: purple;
height: 2em;
}
nav {
position: absolute;
overflow: hidden;
left: 20px;
right: 20px;
top: 0.5em;
height: 1em;
}
ul {
position: absolute;
left: 0;
top: 0;
-webkit-transition: left .3s ease; /* for smooth sliding */
}
li {
float: left;
background: green;
margin: 0 10px;
}
.next,
.prev {
cursor: pointer;
position: absolute;
top: 0;
width: 0;
height: 0;
border-top: 16px solid transparent;
border-bottom: 16px solid transparent;
}
.next {
border-left: 10px solid red;
right: -15px;
}
.prev {
border-right: 10px solid red;
left: -15px;
display: none;
}
JavaScript
var ulWidth = 0;
var navWidth = 0;
var leftOffset = 0;
/* get the <nav> width */
navWidth = $('nav').width();
/* let's count the real width of <ul> */
$('ul li').each(function(){
ulWidth += $(this).width();
ulWidth += 20; /* cause margins */
});
$('ul').width(ulWidth); /* providing one-line list */
/* changing left coordinate to slide our carousel */
$('.next').click(function(){
leftOffset = $('ul').position().left;
/* This is difference between <nav> right and <ul> right */
var rightsDifference = navWidth - ( ulWidth - Math.abs(leftOffset) );
if (rightsDifference < 0) {
leftOffset -= 100;
$('ul').css('left', leftOffset + 'px');
}
if(rightsDifference + 100 >= 0) /* If you think that minus should be here than remember abs */
{
$('.next').hide();
}
/* returning scroll conrol */
var leftsDifference = leftOffset;
if(leftsDifference < 0) {
$('.prev').show();
}
});
$('.prev').click(function(){
leftOffset = $('ul').position().left;
/* This is difference between <nav> left and <ul> left */
var leftsDifference = leftOffset;
if(leftsDifference < 0)
{
leftOffset += 100;
$('ul').css('left', leftOffset + 'px');
}
if(leftsDifference+100 >=0 )
{ /* this difference become real */
$('.prev').hide();
}
var rightsDifference = navWidth - ( ulWidth - Math.abs(leftOffset) );
if(rightsDifference < 0) {
$('.next').show();
}
});