tags:

views:

46

answers:

3

Hello,

I have 1 div that will contain 3-5 divs with the same class. Below the div is an anchor. I would like for when this anchor is clicked it will hide the first div and then show the second. Another click would show the next and so on. I have set display:none on all divs but the first so only one is currently showing. I just can't figure out how to hide the first and then show the second, then third, then next when clicking the anchor.

<div class="container-div">
<div class="inner-div">...</div>
<div class="inner-div" style="display:none;">...</div>
<div class="inner-div" style="display:none;">...</div>
<a href="#" class="more">More</a>
</div>

So when the more anchor is clicked it would show one inner-div one at a time. Any suggestions or ideas would be greatly appreciated. Also, I would like to use jquery to accomplish this.

+2  A: 

You could do something like:

$(".inner-div:visible").hide().next().show();

This would find the first visible div with that class, then navigate to the next child and show it.

This assumes that:

  1. The divs are siblings
  2. If the last div is showing, clicking the button will just hide it and show nothing.

To cycle back to the beginning is slightly trickier. I might do something like:

var next = $(".inner-div:visible").hide().next();
if (next.length > 0)
    next.show();
else
    $(".inner-div:first").show();

To instead simply stop cycling after the last div is showing, you could do:

var current = $(".inner-div:visible");
if (current.next().length > 0)
    current.hide().next().show();
VoteyDisciple
Rock! Thanks so much! This is working great but the only problem is that after the last div is shown, and I click more the div disappears. Is it possible to loop back to the first? Thanks again for your help!
pixelflips
Ouch. Just noticed you had mentioned that the last will hide. Sorry about that. Is there any way to prevent that or maybe loop back to the first?
pixelflips
I've edited with a solution for looping back around to show the first div again after the last is hidden.
VoteyDisciple
Would it be possible just to stop the script once the last div is shown?
pixelflips
I've added a solution for that as well.
VoteyDisciple
A: 

how about giving the invisible divs an additional class, say invisible, and then specify the display:none in the css for that class.

Whenever the link is pressed add the class to any div in the container that hasn't already got it, and then remove the class from the next div with the inner-divclass (or the first inner-div if you are at the buttom)

Jon List
A: 

don't know if you are restricted by your requirements, but I think cycle or carousel plugins will also work fine for this kind of work.

TheVillageIdiot
Thanks for the tip. I would love to use a plugin but that would have to be a last resort due to requirements. :( Thanks again and I bookmarked the link for future projects.
pixelflips