Reputation: 123
I am tring to build a small slider that has multiple boxes. I have 8 (for example) and I need to have 4 displayed at a time. They are like small banners that I want to slide up.
Here is my code so far:
HTML:
<div id="boxes">
<div class="current">1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div class='box hide'>5</div>
<div class='box hide'>6</div>
...
</div>
CSS:
#boxes div{
width:400px;
height:60px;
background-color: red;
color:white;
margin: 20px 0;
}
.hide{display:none;}
Javascript:
$(function(){
setInterval(show_boxes, 2000);
})
function show_boxes(){
var curBox = $("#boxes div.current");
var nxtBox = curBox.next();
if(nxtBox.length == 0){
nxtBox = $("#boxes div:first");
}
curBox.removeClass('current').addClass('hide');
nxtBox.addClass('current').removeClass('hide');
}
Upvotes: 1
Views: 77
Reputation: 14308
I would do it something like this:
function show_boxes() {
// cache the boxes wrapper (for performance)
var $boxes = $('#boxes');
// fetch the box we want to hide, which is on top of the list
var $toHide = $boxes.find('div:first');
// add it to the end of the list
$boxes.append($toHide);
// hide it
$toHide.addClass('hide');
// show the next box, which is now always the first hidden one
$boxes.find('.hide:first').removeClass('hide');
}
Note that I move the top box to the end of the list each time. This way you will get a nice infinite loop, and you do not have to do complex checks to see which box is the next one to show, and which is the next one to hide.
A demonstration: http://jsfiddle.net/XzmAT/2/
Also I removed the current
class, as it is not needed in my code.
Upvotes: 2