Blankman
Blankman

Reputation: 266960

Determine if collection of elements are visible using JQuery like $(".someClass")

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.

Upvotes: 2

Views: 1357

Answers (4)

Tim Molendijk
Tim Molendijk

Reputation: 1046

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.

Upvotes: 1

Lucas Jones
Lucas Jones

Reputation: 20183

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.

Upvotes: 1

mkoryak
mkoryak

Reputation: 57928

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

how about that?

Upvotes: 9

John Rasch
John Rasch

Reputation: 63435

$(".someClass:visible")

will return the visible ones.

Upvotes: 2

Related Questions