Is there any way that I can check if an element is visible in pure JS (no jQuery) ?
So, for example, in this page: Performance Bikes, if you hover over Deals (on the top menu), a window of deals appear, but at the beginning it was not shown. It is in the HTML but it is not visible.
So, given a DOM element, how can I check if it is visible or not? I tried:
window.getComputedStyle(my_element)['display']);
but it doesn't seem to be working. I wonder which attributes should I check. It comes to my mind:
display !== 'none'
visibility !== 'hidden'
Any others that I might be missing?
If element is regular visible (display:block and visibillity:visible), but some parent container is hidden, then we can use clientWidth and clientHeight for check that.
Plunker (click here)
Use the same code as jQuery does:
So, in a function:
Works like a charm in my Win/IE10, Linux/Firefox.45, Linux/Chrome.52...
Many thanks to jQuery without jQuery!
According to this MDN documentation, an element's
offsetParent
property will returnnull
whenever it, or any of its parents, is hidden via the display style property. Just make sure that the element isn't fixed. A script to check this, if you have noposition: fixed;
elements on your page, might look like:On the other hand, if you do have position fixed elements that might get caught in this search, you will sadly (and slowly) have to use
window.getComputedStyle()
. The function in that case might be:Option #2 is probably a little more straightforward since it accounts for more edge cases, but I bet its a good deal slower, too, so if you have to repeat this operation many times, best to probably avoid it.
The jQuery code from http://code.jquery.com/jquery-1.11.1.js has an isHidden param
So it looks like there is an extra check related to the owner document
I wonder if this really catches the following cases:
This is a way to determine it for all css properties including visibility:
html:
css:
javascript:
It works for any css property and is very versatile and reliable.
I've got a more performant solution compared to AlexZ's getComputedStyle() solution when one has position 'fixed' elements, if one is willing to ignore some edge cases (check comments):
Side note: Strictly speaking, "visibility" needs to be defined first. In my case, I am considering an element visible as long as I can run all DOM methods/properties on it without problems (even if opacity is 0 or CSS visibility property is 'hidden' etc).