views:

42

answers:

3

I have a random amount of DIVs (minimum 1, max of 10)

<div id="container">
<div class="foo">Content</div> <!-- div 1 -->
<div class="foo">Content</div> <!-- div 2 -->
<div class="foo">Content</div> <!-- div 3 -->
<div class="foo">Content</div> <!-- div 4 -->
<div class="foo">Content</div> <!-- div 5 -->
<div class="foo">Content</div> <!-- i need this one hidden -->
<div class="foo">Content</div> <!-- and this one -->
</div>

I want the first 5 divs to be visible (either with .show() or with a class, doesn't matter). Any additional DIVs should be hidden.

I then simulate the "closing" of a div with:

$('.foo').click(function(){
    $(this).fadeOut('slow');    
});

which removes the clicked div, causing all the divs below to move up one. This is my desired effect.

however, I need some logic here.

If I have less than 5 DIVS, the close facility should be disabled. If I have more than 5 DIVs, then when a div is "closed", i want the next "hidden" div to become visible.

I can add IDs to each DIV if required with IDs like "foo1" "foo2" etc.

hope this is clear enough

thanks

A: 
$('.foo').each(
   function(index,element) {
       if(index>5) $(element).hide();
   }
)
dvhh
+5  A: 

Something like this should work:

$("#container .foo:gt(4)").hide();

$("#container").delegate(".foo", "click", function() {
    if(!$("#container .foo:hidden").length) return;
    $(this).fadeOut('slow', function() { 
        $(this).siblings(":hidden:first").fadeIn()
               .end().remove();
    });
});

You can test it out here. What this does is hides all past 5 using the :gt(4) (0-based) selector. Then we're using .delegate() for efficiency (though a .click() would work too). If there aren't any more hidden, there's no effect. If there are more hidden, fade out the one we clicked, at at the end of the fade show the :first :hiddden one, and .remove() the one we faded out completely.

Nick Craver
or ugly css! .foo+.foo+.foo+.foo+.foo+.foo { display: none; } anything with more than 5 preceding .foo siblings will get hidden. if you remove it anyway. it doesnt have the fadeIn support though
DoXicK
@DoXicK - I think you overlooked the `.end()` call, it's not the fadeing-in sibling I'm removing, it's `$(this)` :)
Nick Craver
would +2 - perfect as ever, thanks.
Ross
A: 
$('#container div.foo').click(function() {
  if ($(this).index() >= 5) ...; //etc
}
James Westgate
if you have a thousand results, you will be executing that function a thousand times. what about using :gt(4) in combination with a direct hide() ? it's way faster
DoXicK
But we dont, we have max 10 as the OP stated - and we have the ability to modify the code based on each index... anyway
James Westgate