views:

471

answers:

4

Hi,

I have a collection of elements on my page, and I want to see if they are visible or not currently.

So:

$(".someClass")

How can I loop through and figure this out? because if it is visible, i have to fire another function.

+2  A: 
$(".someClass:visible")

will return the visible ones.

John Rasch
+7  A: 
$(".someClass").each(function(){
  if($(this).is(":visible")){
    //item is visible: do something
   }
});

how about that?

mkoryak
Yeah, I'm pretty sure this is exactly what he's looking for
John Rasch
Yep, I don't think I can optimize it any further. Good work.
KyleFarris
$('.someClass:visible').each(function(){ // item is visible, do something}Would that not be more optimized?
Matt
That if statement looked beautiful and readable.
Dykam
+1  A: 

What you could do:

$(".someClass").each(function(x) { if ( x.style.display != "none" && x.style.visibility != "hidden" ) { your_function(); } });

where your_function() is the name of your function.

Lucas Jones
A: 

All solutions in terms of $('.someClass').is(':visible') are unreliable. All it tells us is if a particular element has a styling of display:none or visibility:hidden. This is not the same as whether an element is visible!

Consider a situation like this:

<div style="display:none;"><div class="someClass"></div></div>

Everybody can see that the element designated by $('.someClass') is invisible. But $('.someClass').is(':visible') will return true!

The only water-proof solution is to not only check for is(':visible') on the $('.someClass'), but on all of its parent elements as well. Only if for none of the parents holds that is(':visible') === false, we can conclude that $('.someClass') is actually visible.

Tim Molendijk
Actually, they've overhauled the logic of :visible and :hidden selectors in version 1.3.2 to account for this case: http://docs.jquery.com/Release:jQuery_1.3.2#:visible.2F:hidden_Overhauled
dalbaeb
Brilliant, I missed that improvement! Thanks
Tim Molendijk