Reputation: 1363
I have a code which will navigate between each div
on button click.
If I have 5 divs
and I click next
button 5 times it reaches end. But when I click 6th time, it is showing 1 st div
again like a loop. Same is the case with previous
button. How to stop going from 5 to 1? And if I want to go back to div 1
from,the only way should be to click previous
button and go.
html :
<div class="divs">
<div class="cls1">1</div>
<div class="cls2">2</div>
<div class="cls3">3</div>
<div class="cls4">4</div>
<div class="cls5">5</div>
<div class="cls6">6</div>
<div class="cls7">7</div>
</div>
<a id="next">next</a>
<a id="prev">prev</a>
js:
$(document).ready(function(){
$(".divs div").each(function(e) {
if (e != 0)
$(this).hide();
});
$("#next").click(function(){
if ($(".divs div:visible").next().length != 0)
$(".divs div:visible").next().show().prev().hide();
else {
$(".divs div:visible").hide();
$(".divs div:first").show();
}
return false;
});
$("#prev").click(function(){
if ($(".divs div:visible").prev().length != 0)
$(".divs div:visible").prev().show().next().hide();
else {
$(".divs div:visible").hide();
$(".divs div:last").show();
}
return false;
});
});
Upvotes: 1
Views: 79
Reputation: 2793
You should remove the else
block from each click callback. When no more div
s are visible the else
block will hide all visible div
s and show the first when clicking next, or the last when clicking previous.
$(document).ready(function(){
$(".divs div").each(function(e) {
if (e != 0)
$(this).hide();
});
$("#next").click(function(){
if ($(".divs div:visible").next().length != 0)
$(".divs div:visible").next().show().prev().hide();
return false;
});
$("#prev").click(function(){
if ($(".divs div:visible").prev().length != 0)
$(".divs div:visible").prev().show().next().hide();
return false;
});
});
Upvotes: 1
Reputation: 327
just update the next and prev click function so it wont return back to the first and last div
$("#next").click(function(){
if ($(".divs div:visible").next().length != 0)
$(".divs div:visible").next().show().prev().hide();
return false;
});
$("#prev").click(function(){
if ($(".divs div:visible").prev().length != 0)
$(".divs div:visible").prev().show().next().hide();
return false;
});
Upvotes: 1