views:

1280

answers:

4

Hi,

Before I call:

$('myObject').show();

I want to know if it is currently hidden or visible.

+3  A: 

You can test this with the css() function:

if ($('myObject').css('display') == 'none') {
  $('myObject').show();
}

EDIT:

Wasn't aware of how cool the :hidden selector is. My suggestion is still useful for testing other attributes, but Alex's suggestion is nicer in this case.

Adam Lassek
I think the value for display is 'none', or for visibility is 'hidden'.
CodeMonkey1
Yes, I was already editing that. Thanks.
Adam Lassek
The :hidden and :visible selectors check both display and visibility as well as hidden inputs.
CodeMonkey1
+17  A: 

There's 2 ways to do it, that I know of:

if ($('#something').is(':hidden')) { }

or

if ($('#something').is(':visible')) { }

They should both work.

You can also do something like this:

$('#something:hidden').show();
$('#something:visible').hide();

Which will only call .show() if the item is already hidden, or only call .hide() if the item is already visible.

Alex Fort
+7  A: 

You could also use the Toggle $(this).toggle();

rizzle
+1, This is a much simple solution if you only want to toggle state of the object.
Alex Fort
+2  A: 

From jQuery FAQ:

 var isVisible = $('myObject').is(':visible');
 var isHidden = $('myObject').is(':hidden');
JacobM