Show a set number of <li>s and then hide them to reveal another set number of <li>s
I am trying to create a carousel, using floated list items.
When Next is pressed the current 4 visible li
s are hidden and the next 4 shown for as many times as needed. Though, there may not always be another 4 to show, as in the case below there would only be 2 more to display.
When Prev is pressed the current 4 visible li
s are hidden and the previous 4 shown.
It doesn't need to loop i.e. if Next is pressed enough times it will reach the end, it wont just start back from the beginning again.
http://jsfiddle.net/tw16/5NB6G/
HTML:
<div id="left">Prev</div>
<ul>
<li>Test 1</li>
<li>Test 2</li>
<li>Test 3</li>
<li>Test 4</li>
<li>Test 5</li>
<li>Test 6</li>
</ul>
<div id="right">Next</div>
jQuery/JavaScript:
var listLength = $('ul li').length;
var listCount开发者_高级运维er = 0;
$("#right").click(function() {
if (listCounter == listLength - 1) {
$("ul li").show(400);
listCounter = 0;
}
else {
$('ul li').eq(listCounter).hide(400);
listCounter++;
}
});
Unfortunately, I haven't been able to adapt the code to the requirements above.
No reason to reinvent the wheel. Check out jCarousel.
I experimented a bit and came up with the following:
var total = $('ul li').length;
var start = 0;
var count = 4;
update = function() {
for (var i = 0; i < total; i++) {
el = $("ul li").eq(i);
if (i >= start && i < start + count)
el.show(400);
else
el.hide(400);
}
}
$("#right").click(function() {
start += count;
if (start >= total)
start = 0;
update();
});
$("#left").click(function() {
start -= count;
if (start < 0)
start = Math.floor(total / count) * count;
update();
});
See http://jsfiddle.net/5NB6G/43/ for a live demo.
EDIT: I just noticed that you don't need wrapping over the end/beginning. You can use the following then in conjunction with the update
function defined above:
$("#right").click(function() {
start += count;
if (start >= total)
start -= count;
update();
});
$("#left").click(function() {
start -= count;
start = start < 0 ? 0 : start;
update();
});
精彩评论