46

Just wondering how to determine a jQuery statement like this

if( $("#test").css('display', 'block') == true) {
   return true;
}

Basically, I want to be able to determine IF an element has is currently being shown or hidden via the "display:block" attribute ?

Tom
  • 463
  • 1
  • 4
  • 4

3 Answers3

88

Use

if( $("#test").css('display') == 'block') {

I'm fairly sure .css(), returning a calculated value, will always return a lower case result - the docs say nothing on this. To make totally sure, you could do a

if( $("#test").css('display').toLowerCase() == 'block') {

while you can rely on display giving reliable results, note that some CSS properties will not always show up the way they were defined. For example

a { color: red }

will turn out rgb(255,0,0); when queried using .css().

Pekka
  • 442,112
  • 142
  • 972
  • 1,088
  • @Tom you are checking whether `test1` has `display: none` which it doesn't have. Do you mean `display != 'block'`? – Pekka May 08 '11 at 17:49
  • @Pekka - Thanks for the response :) Nah, I wanted to check if #test is block - and if it is block then show test1 ? – Tom May 08 '11 at 17:49
  • @Tom yeah, I see now. Try this: http://jsfiddle.net/eEF9Y/4/ you didn't select jQuery in the menu to the left, the code works. – Pekka May 08 '11 at 17:51
11

You can use isvisible and is hidden also

if ( $('#test').is(':visible')){
kobe
  • 15,671
  • 15
  • 64
  • 91
  • 3
    This will actually work better if visibility is what you want to determine, +1 – Pekka May 08 '11 at 17:10
  • This is very interesting. I was trying to pause some videos that were hidden on mobile by a media query that applied display:none; to them, but consoling $(elm).css('display') returned 'block', which was their default value. Your answer did the trick with them. Thanks a lot! – Rorok_89 Mar 21 '18 at 11:34
1

I think the only way to test this is by comparing with actual values:

function displayHidden(elem) {
    return $(elem).css('display') === 'hidden';
}
sdleihssirhc
  • 42,000
  • 6
  • 53
  • 67