JSFiddle - React, Tailwind, and code Playground
HTML
<input type=button onclick="$('.item').eq( 5).magicScrollTo()" value="Test 5" />
<input type=button onclick="$('.item').eq(10).magicScrollTo()" value="Test 10" />
<input type=button onclick="$('.item').eq(20).magicScrollTo()" value="Test 20" />
<input type=button onclick="$('.item').eq(30).magicScrollTo()" value="Test 30" />
<div id="botmenu">
<div id="left"><</div>
<div id="right">></div>
<div id="middle">
<div id="items">
<div class="item">
<img src="http://placehold.it/40x40">
</div>
<div class="item">
<img src="http://placehold.it/40x40">
</div>
<div class="item">
<img src="http://placehold.it/40x40">
</div>
<div class="item">
<img src="http://placehold.it/40x40">
</div>
<div class="item">
<img src="http://placehold.it/40x40">
</div>
<div class="item">
<img src="http://placehold.it/40x40">
</div>
<div class="item">
<img src="http://placehold.it/40x40">
</div>
<div class="item">
<img src="http://placehold.it/40x40">
</div>
<div class="item">
<img src="http://placehold.it/40x40">
</div>
<div class="item">
<img src="http://placehold.it/40x40">
</div>
<div class="item">
<img src="http://placehold.it/40x40">
</div>
<div class="item">
<img src="http://placehold.it/40x40">
</div>
<div class="item">
<img src="http://placehold.it/40x40">
</div>
<div class="item">
<img src="http://placehold.it/40x40">
</div>
<div class="item">
<img...
CSS
#botmenu
{
position: fixed;
width: 100%;
height: 50px;
bottom: 0px;
background: fuchsia;
text-align:center;
}
#middle
{
background: red;
overflow: hidden;
height: 50px;
}
#items
{
background: yellow;
}
.item
{
padding: 5px;
float: left;
}
#left{
float:left;
width:30px;
margin-top: 15px;
height: 20px;
background:cyan;
}
#right{
float:right;
width:30px;
margin-top: 15px;
height: 20px;
background:cyan;
}
JavaScript
(function($){ //Run on load / DOMReady
$.fn.magicScrollTo = function(){
var middle = $("#middle");
var currentScrollLeft = middle.scrollLeft();
var width = middle.width();
var newScrollLeft = this.offset().left + currentScrollLeft - middle.offset().left;
if(newScrollLeft >= currentScrollLeft && newScrollLeft <= currentScrollLeft + width - this.outerWidth()) return;
if(newScrollLeft > currentScrollLeft){ //If the element is at the right side
newScrollLeft = newScrollLeft - width + this.outerWidth();
}
middle.animate({
scrollLeft: newScrollLeft,
}, 'fast')
this.css('background', 'yellow'); //Demo purpose only!
}
})(jQuery);
var totalWidth = 0;
$(".item").each(function(index, value) {
totalWidth += $(value).outerWidth();
});
$("#items").width(totalWidth);
$("#left").click(function() {
$("#middle").animate({
scrollLeft: "-=50px"
}, 'fast');
});
$("#right").click(function() {
$("#middle").animate({
scrollLeft: "+=50px"
}, 'fast');
});