Read more

Check whether an element is visible or hidden with Javascript

Henning Koch
July 08, 2011Software engineer at makandra GmbH

jQuery

You can say:

$(element).is(':visible')
Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

and

$(element).is(':hidden')

jQuery considers an element to be visible if it consumes space in the document. For most purposes, this is exactly what you want.

Native DOM API

Emulate jQuery's implementation Show archive.org snapshot :

element.offsetWidth > 0 && element.offsetHeight > 0;

jQuery > 3

Query 3 slightly modifies the meaning of :visible (and therefore of :hidden).

Emulate jQuery's implementation:

!(window.getComputedStyle(element).display === "none")

Prototype

Don't use Element#visible(), it just checks if a CSS attribute display: none exists. This is too naive for most cases.

Emulate jQuery's implementation Show archive.org snapshot instead:

element.offsetWidth > 0 && element.offsetHeight > 0;

Or maybe you'd even like to patch Prototype so it behaves like jQuery:

Element.addMethods({
  visible: function() {
    return offsetWidth > 0 && offsetHeight > 0;
  }
});
Posted by Henning Koch to makandra dev (2011-07-08 13:52)