Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check element's visibility via javascript?

Tags:

javascript

css

I'm interested in a way to check whether an element has display:none style explicility (ie style="display:none"), has a class that has (or inherits) this style, or one of its parents is hidden (and my element inherits this)

Case1:

<body><div><span style="display:none;">Some hidden text</span></div>

or

<body><div style="display:none;"><span>Some hidden text</span></div>

Case2:

SomeClass {   display:none;   }
<body><div class="SomeClass"><span>Some hidden text</span></div>

Thanks,

like image 207
Haytham Avatar asked Aug 27 '09 19:08

Haytham


People also ask

How can we check element visibility?

We can do the following to check an element's visibility in the viewport: Get the bounding rect of the DOM element using the getBoundingClientRect . This method returns an object with an element's width, height, and position relative to the viewport.

What is element visibility in Javascript?

The visibility property sets or returns whether an element should be visible. The visibility property allows the author to show or hide an element. It is similar to the display property.

How do I check if an element is hidden in Javascript?

Another way to check if an element is hidden is to use the window. getComputedStyle() method. It will return the display property value of the object. We can check if the string is equal to none meaning the element is hidden and do something.

How do you check if an element is visible on the web page in JS?

Summary. Use the getBoundingClientRect() method to get the size of the element and its relative position to the viewport. Compare the position of the element with the viewport height and width to check if the element is visible in the viewport or not.


1 Answers

You are looking for one solution to two different scenarios.

The first scenario is getting the cascaded/computed style for a css property. See this answer for how to do that.

The second scenario is detecting if any of an element's parents are hidden. This requires traversing and is cumbersome and slow.

You can take the solution outlined here (and employed by jQuery/Sizzle since 1.3.2), and just read the dimensions of the element:

var isVisible = element.offsetWidth > 0 || element.offsetHeight > 0;

If it has dimensions then it is visible in the sense that it takes up some rectangular space (however small) in the document. Note that this technique still has some downsides for certain elements in certain browsers, but should work in most cases.

like image 123
Crescent Fresh Avatar answered Sep 30 '22 16:09

Crescent Fresh