Checking if an element is hidden with jQuery – the correct method

by . Originally posted

Over the last couple of days I’ve been reviewing code submitted by other programmers for an external project. Two of these developers, who shall remain nameless, were checking whether elements in a form were visible or not. This is quite a common scenario, jQuery is often used to hide, add and remove elements dynamically these days.

They were using the following method, which to give them credit, did work for 99% of their cases:

if( $("form#formID input#inputID").css('display') != 'none' ) {

As mentioned above, this method works most of the time when detecting whether an element has been hidden (display CSS attribue set to none).

Problems with jQuery checking display = none

However, in their situation, they then started hiding and showing different panels within the same form. This is where problems arose.

Checking whether an element has a display value other than none doesn’t mean its visible; if a parent element is set to hidden yet our form element is set to display correctly, the form element will be still hidden thanks to its parent.

E.g.

<form id='formID' style='display: none'>
<input id='inputID' type='text' style='display: inline-block' />
</form>

Here our textbox won’t be visible, yet the above snippet of jQuery will return TRUE because the textbox isn’t itself set to be hidden.

Simple jQuery :visible selector solution

The simple solution is to modify your jQuery to be:

if( $("form#formID input#inputID").is(":visible") ) {

This will select our textbox and then test correctly whether it is visible in the DOM. This check will make sure all parent elements are visible too, as well as the original CSS display attribute.

Hope this helps a few of you guys out,

Categories: Computing, Fixes & Solutions, jQuery

Tags: , ,

2 Comments

Leave a Reply

Your email address will not be published.

Links and useful footery things…

Copyright © 2017 Paul Joyce. Follow me on Twitter or perhaps Google+