I'm trying to 'copy' the mechanics of boostrap caroussel ( link ). Forward is fine, not the same bootstrap mechanic but visually it is, although it is not the best way because I'm adding infinitely .item
to the div (thanks for suggestions to get around this), and back does not work at all.
var item_width = $('#slider-wrapper .item').width();
var num_of_items = $('#slider-wrapper .item').length;
var index_item_on = 0;
$('#slider-wrapper').width(item_width * num_of_items);
$('#next').on('click', function() {
$('#slider-wrapper .item').eq(index_item_on).clone().appendTo('#slider-wrapper');
$('#slider-wrapper').width($('#slider-wrapper').width() + item_width); // ajustar comprimento da div mãe
$('#slider-wrapper').animate({
'margin-left': '-=' +item_width+ 'px'
},500);
index_item_on++;
if(index_item_on == 0) {
index_item_on = 0;
}
});
$('#prev').on('click', function() {
$('#slider-wrapper').animate({
'margin-left': '+=' +item_width+ 'px'
}, 500);
index_item_on--;
if(index_item_on < 0) {
$('#slider-wrapper .item').last().clone().prependTo('#slider-wrapper');
index_item_on = num_of_items - 1;
}
});
#slider-window {
width: 150px;
height:150px;
border: 1px solid;
position: relative;
overflow:hidden;
}
#slider-wrapper .item {
width: 150px;
height: 150px;
background-position: center center;
background-size: cover;
background-repeat: no-repeat;
float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="slider-window">
<div id="slider-wrapper">
<div class="item" data-item="1">HEYA 1</div>
<div class="item" data-item="2">HEYA 2</div>
<div class="item" data-item="3">HEYA 3</div>
</div>
</div>
<h2>
<b id="prev">← </b>
<b id="next">→ </b>
</h2>