jquery .is(“:visible”) not working in Chrome

if ($("#makespan").is(":visible") == true) { 
    var make = $("#make").val(); 
}
else {
    var make = $("#othermake").val(); 
}

Make:<span id=makespan><select id=make></select><span id=othermakebutton class=txtbutton>Other?</span></span><span id=othermakespan style="display: none;"><input type=text name=othermake id=othermake>&nbsp;-&nbsp;<span id=othermakecancel class=txtbutton>Cancel</span></span>

The above code runs smooth in Firefox but doesn't seem to work in Chrome. In Chrome it shows .is(":visible") = false even when it is true.

I am using following Jquery Version: jquery-1.4.3.min.js

jsFiddle Link: http://jsfiddle.net/WJU2r/4/

Answers


It seems jQuery's :visible selector does not work for some inline elements in Chrome. The solution is to add a display style, like "block" or "inline-block" to make it work.

Also note that jQuery has a somewhat different definition of what is visible than many developers

Elements are considered visible if they consume space in the document. Visible elements have a width or height that is greater than zero.

Elements with visibility: hidden or opacity: 0 are considered visible, since they still consume space in the layout.

Elements that are not in a document are considered hidden; jQuery does not have a way to know if they will be visible when appended to a document since it depends on the applicable styles.

All option elements are considered hidden, regardless of their selected state.

During animations that hide an element, the element is considered visible until the end of the animation. During animations to show an element, the element is considered visible at the start at the animation.

In other words, elements that consume space are visible, which means the element must have a width and a height to consume space and be visible. On the other hand, even if it's visibility is set to hidden or the opacity is zero, it's still :visible to jQuery as it consumes space, which can be confusing when the CSS explicitly says it's visibility is hidden.

The easy way to look at it, is that if you can see the element on the screen, even if you can't see it's content, it's transparent etc., it's visible, i.e. it takes up space.

I cleaned up you markup a little and added a display style (i.e. setting the elements display to "block" etc), and this works for me:

FIDDLE

Official API reference for :visible


Need Your Help

Can we cast a generic object to a custom object type in javascript?

javascript oop object

For example, I already have this object somewhere in the code, it is a generic object:

Uninstall a Windows driver when the hardware is not connected

windows hardware uninstall drivers

I am developing a Windows C++ application that drives a motor controller that is plugged on USB.