jQuery :hidden/:visible and animation oddities


Beware that in some cases your jQuery animations (e.g. fadeIn(), fadeOut() and others) may not run, because jQuery may think that the DOM node, on which you request the animation, is not visible.

When and how can this be a problem?

In most cases, of course, the DOM node will indeed be invisible and this will not be an issue.

There are, however, some exceptional cases. Suppose you have an absolutely positioned container, with no explicit width and height, which in turn has absolutely positioned child elements. If you, for example, set the opacity of the container to 50%, its absolutely positioned children will also become 50% opaque. If you set the CSS display to none, its children will again be hidden.

However, the container is technically invisible.

That’s because the container’s browser reported outerWidth and outerHeight are both zero, which, for jQuery, means that the element is invisible — see [1] — that’s the way the :hidden and :visible selectors work in jQuery 1.3.2 and newer.

Here comes the problem: if you run any animations on the container — for example fadeOut() — it will be optimized by jQuery and will not execute, due to the fact that jQuery sees the element as not visible (which is correct and the clever thing to do in most cases).

The solution is quite simple — you may just set an (even random) nonzero width or height to the container. As its children are absolutely positioned, it should not affect anything, but your animations will run.

[1] http://docs.jquery.com/Release:jQuery_1.3.2#:visible.2F:hidden_Overhauled

  1. No comments yet.

Comments are closed.