mplungjan
mplungjan

Reputation: 177885

Check if all divs are hidden

JSFIDDLE

$(document).ready(function() {
    $(".chk").click(function() {
        $(".chk:checked").each(function() {
           $("."+this.id).show();
        });       
        $(".chk:not(:checked)").each(function() {
           $("."+this.id).hide();
        }); 
        // give a message if nothing left to show       
    });  
}); 

<label>
    <input class="chk" type="checkbox" checked="checked" id="course">Courses
</label> 
<label>
    <input class="chk" type="checkbox" checked="checked" id="morning">Morning
</label> 
<label>
    <input class="chk" type="checkbox" checked="checked" id="evening">Evening
</label> 
<ul>
    <li class="courseBox course">Course</li>
    <li class="courseBox course evening">Course, Evening</li>
    <li class="courseBox morning">Morning </li>
</ul>​

How do I most elegantly know if all the affected divs were hidden?


UPDATE: If you need to check after a fadeOut, you need to put the check in the callback:

$(".chk:not(:checked)").each(function() {
  $("."+this.id).fadeOut(function() {
    if (!$('.courseBox:visible').length) {
      alert('all are hidden');
    }
  });
}); 

Upvotes: 0

Views: 2429

Answers (5)

ShankarSangoli
ShankarSangoli

Reputation: 69905

Your code can be simplified as below.

$(document).ready(function() {
    $(".chk").click(function() {
        $("." + this.id).toggle(this.checked);
        if($(".courseBox:visible").length == 0){
            alert("All divs are hidden");
        }
    });        
});   

Working demo - http://jsfiddle.net/ShankarSangoli/JrAhR/13/

Upvotes: 0

vdeantoni
vdeantoni

Reputation: 1968

Count the visible li elements:

 if ($('ul li:visible').length == 0) {
  alert("Everything is gone!")
 }

More info:

:visible selector

Upvotes: 3

Chris Pratt
Chris Pratt

Reputation: 239290

You need the :visible selector:

if ($('div:visible').length == 0) alert('no more divs!');

Upvotes: 2

user1106925
user1106925

Reputation:

if (!$('.courseBox:visible').length)
    alert('all are hidden');

http://jsfiddle.net/JrAhR/6/

Upvotes: 4

El Guapo
El Guapo

Reputation: 5781

You could try this:

$('ul').find(':hidden').length

This will give you the number of elements under "ul" that are hidden

Upvotes: 0

Related Questions