Detect visibility of elements after adding Display: none using javascript

I have four divs in my 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 the javascript click event is display: none

added to them to hide. So I want to do something when the elements are not visible.

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

      

The above code does not work because it counts the number of visible items before the click event (even if all classes have a display: none it gives

count of 4).

I am using a function change();

to select toggle a display property.

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

+3


source to share


3 answers


The problem is that your boxes are being hidden with a help fadeOut()

that runs asynchronously. This means that when checking the number of elements, the :visible

animation is not finished yet, so they are still technically visible.

To achieve the result you want, you must run your code in a method callback fadeOut()

. Try the following:



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

      

Updated script

+1


source


Basically every time you handle the onclick event you should then check each element to see if it shows the css parameter 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");
});

      

+1


source


Html

<select id="showhide">
    <option>hide</option>
    <option>show</option>
</select>
<div id="boxes">
 <div class="inner-box">one</div>
 <div class="inner-box">two</div>
 <div class="inner-box">three</div>
 <div class="inner-box">four</div>
</div>  

      

Script

$('.inner-box').hide();
$('#showhide').on('change',function(){
    $('.inner-box').toggle();
    alert($('#boxes').children(':visible').length);
});
alert($('#boxes').children(':visible').length);  

      

Demo

0


source







All Articles