Can I determine the current state of the display CSS style for a given element using JS

css, javascript

Solution

From the jQuery/Sizzle source-code:

elem.offsetWidth > 0 || elem.offsetHeight > 0 // visible
elem.offsetWidth === 0 || elem.offsetHeight === 0  // hidden

where `elem` is a DOM element.

Now I'm not entirely sure why they say that an element is visible if either dimension is bigger than zero. I'd say that both dimensions should be bigger than zero for it to qualify as 'visible', but I trust they know better. (Maybe one null dimension and another non-zero dimension is not even possible within the browser).

Update: There's another discussion on the topic and an alternate solution (haven't tried it though): How do I check if an element is really visible with JavaScript?

Problem

I wish to write a simple javascript function that toggles the visibility of a given element. Problem is, immediately after the page load, the initial style is unknown (at least to me). How can I determine what the current value of a given element's display style element is?

Original source

Related problems