jquery show/hide divs and a counter
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 --&g开发者_StackOverflowt;
<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.
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.
$('.foo').each(
function(index,element) {
if(index>5) $(element).hide();
}
)
$('#container div.foo').click(function() {
if ($(this).index() >= 5) ...; //etc
}
精彩评论