3
I’m trying to 'copy' the mechanics of boostrap Caroussel (http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_carousel&stacked=h). Forward walks well, it is not the same mechanic of the bootstrap but visually it is, although not the best form as I add infinitely .item
à div (I appreciate 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>
<div id="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>
Using prepend and append would not be easier than using insertBefore and After?
– MoshMage
Edited, managed to solve part of the problem, Obgado @Moshmage
– Miguel