Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect elements' visibility after adding Display:none using javascript

I have four divs in a main container.

<div id="boxes">
    <div class="inner-box"></div>
    <div class="inner-box"></div>
    <div class="inner-box"></div>
    <div class="inner-box"></div>
</div>

After a javascript click event, display: none is added to them to hide. So I want to do something when no elements are visible.

if ($('#boxes').children(':visible').length == 0) 

The above code does not seem to be working because it counts the number of visible elements before the click event (even if all the classes have display: none it gives the count 4).

I'm using change(); function for select to toggle the display property.

Demo: http://jsfiddle.net/wnzavyom/1/

like image 442
Rahul Avatar asked Sep 18 '26 02:09

Rahul


2 Answers

Basically every time you process the onclick event you have to then check each item to see if it exhibits the css setting display: none

(Demo)

JAVASCRIPT

$('.inner-box').on("click",function(){
    $(this).css("display","none");
    var visible = false;
    $('.inner-box',$(this).parent()).each(function(){
        if($(this).css("display") !== "none") visible = true;
    });
    if(!visible) alert("All gone");
});

The issue you have is because your boxes are being hidden using fadeOut() which runs asynchronously. This means that when you check the number of :visible elements the animation has not yet finished, so they are still technically visible.

To achieve what you need you should run your code in the callback of the fadeOut() method. Try this:

$('#filter select').change(function () {
     $('.inner-box').fadeOut(function() {
         if ($('#boxes').children(':visible').length == 0) {
             alert('all boxes hidden');
         }
     });
});

Updated fiddle

like image 22
Rory McCrossan Avatar answered Sep 20 '26 17:09

Rory McCrossan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!