DA.
DA.

Reputation: 40671

jQuery is(':visible') acting funny.

I'm running into a strange problem with testing an object's visibility with jQuery.

I have this test JS:

alert($myObject.css('display'));
alert($myObject.is(':visible'));

The first alert displays 'block' which makes sense as firebug clearly shows that it is set to display: block and you can see the object on the page in the browser.

The second alert, though, displays 'false'. Which doesn't make any sense to me at all.

Am I misunderstanding the use of is(':visible')?

Upvotes: 6

Views: 5688

Answers (5)

kintsukuroi
kintsukuroi

Reputation: 1479

I had the same issue. I solved it checking the .height() AFTER the toggle call. Like this:

// detect jQuery toggle state
if ($('#toggled_element').height() > 0) {
    // do this, it's visible
}
else {
    // do this, it's not visible
}

Upvotes: 0

DA.
DA.

Reputation: 40671

So, the answer:

If someone else attaches a CLICK event to your object that you were previously unaware of, that event may be screwing up any logic you were trying to use. ;)

Alas, that's what happened here. Another click event had been attached to this object that was set to hide its parent. That was firing first--before my logic checked to see if it was visible.

In the end: user error.

There should be some form of reputation penalty when it's a user-error problem. ;)

Upvotes: 3

Anthony Grist
Anthony Grist

Reputation: 38345

From the :visible Selector documentation:

Elements can be considered hidden for several reasons:

  • They have a CSS display value of none.
  • They are form elements with type="hidden".
  • Their width and height are explicitly set to 0.
  • An ancestor element is hidden, so the element is not shown on the page.

Check that none of these other conditions are true.

Upvotes: 3

Tadeck
Tadeck

Reputation: 137360

Consider this HTML:

<div id="div1" style="display: none;">
    <div id="div2">
        <p>Some div content</p>
    </div>
</div>

and this JavaScript:

$myObject = jQuery('#div2');
alert($myObject.css('display')); // 'block'
alert($myObject.is(':visible')); // false

There are multiple reasons $myObject may not be visible, even though it has display: none style set. See :visible selector docs for details.

Does it make sense now?

Upvotes: 11

KARASZI Istv&#225;n
KARASZI Istv&#225;n

Reputation: 31467

The :visible selector is not equivalent with the display css property.

From the linked documentation, visible is false when:

  • They have a CSS display value of none.
  • They are form elements with type="hidden".
  • Their width and height are explicitly set to 0.
  • An ancestor element is hidden, so the element is not shown on the page.

Upvotes: 4

Related Questions