🔊 I'm running ffconf: UK's best JS & webdev conf. Find out more & get tickets 📢

jQuery *really* :visible

(edit)

On a project I worked with Paul Irish on recently we found that we needed to asset whether an element was visible, but the :visible selector doesn't always do the job.

Update: As of jQuery 1.3.2 this is no longer a problem or required. See Paul's comment below.

The Problem with :visible

The :visible selector works fine if you're asking whether the particular element has been set to invisible (either via the display or visibility CSS style).

However, if the element is hidden because a parent element is set to hidden, the :visible selector returns a false positive.

Solution

If you want to know whether the element is truly visible, you need to step through the parent elements to be 100% sure.

You can do this via a macro selector too:

jQuery.extend(
  jQuery.expr[ ":" ], 
  { reallyvisible : function (a) { return !(jQuery(a).is(':hidden') || jQuery(a).parents(':hidden').length); }}
);

See the working example (source)

An important note: I tried overloading the :visible selector using this new :reallyvisible and it actually breaks the show/hide functions within jQuery - so don't go renaming it!

Posted 17-Oct 2008 under code & jquery & selector.

I am Remy Sharp

I'm a JavaScript developer working professionally on the web since 1999. I run my own consultancy, build products, run training, speak at conferences and curate the UK's best JavaScript event.

Subscribe

Posts, web tech insights, exclusive workshop and training discounts and more, direct to your inbox.

Comments