Question

Introduction

elem.hidden is a new property that allows to hide elements and detect whether they are hidden.

The browser support isn't great so I want to shim it. If I were to shim this property what should it be shimmed to in terms of setting a CSS property through elem.style.

Naive implementation of Shim

Object.defineProperty(HTMLElement.prototype, "hidden", {
  get: function get() {
    return this.style.<???>;
  },
  set: function set(v) {
    this.style.<???> = v ? <???> : <???>
  },
  configurable: true
});

Question

  • Should it set elem.style.display to "none" or <original value> ?
  • Should it set elem.style.visibility to "hidden" or "visible" ?
Was it helpful?

Solution

Browsers are required to implement the hidden attribute as [hidden] { display:none }

See Boris Zbarsky's answer to Force browser to ignore HTML 5 features, and the subsequent comments.

Note that this is done via the user-agent style sheet, so it has a very low specificity, and is easily overridden by a more specific style, even those that don't mention the hidden attribute.

Although I think this is a terrible way to implement the hidden attribute, those are the rules. The nearest you can get to that behaviour is to put [hidden] { display:none } as near as you can to the very start of the first stylesheet on your HTML page, rather than applying directly to the style property of the element, where it will have a very high specificity.

In terms of the element property, the HTML5 spec says "The hidden IDL attribute must reflect the content attribute of the same name.", so that's the only thing you should be adding via Object.defineProperty. However, kennebec's comment that Object.defineProperty isn't much more widely supported is probably valid.

OTHER TIPS

visibility: hidden elements still need to be rendered as they take space on the screen, so display: none is much closer to .hidden = true because display: noneelements can and will be ignored rendering-wise.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top