Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if html parent is hidden

Tags:

html

jquery

I would like to detect when a specific HTML element on the page becomes hidden. This usually happens due to a parent element (maybe few levels up) becoming hidden. Is there a simple way to detect this. Or do I need to traverse the DOM and check each parent?

like image 544
Ron Harlev Avatar asked Sep 24 '10 22:09

Ron Harlev


People also ask

How do you check if an HTML element is hidden?

In JavaScript, the quickest way to check if an element is hidden or visible in DOM is to use the getComputedStyle() method. This method returns the actual values of CSS properties used to render an HTML element in DOM. An HTML element can be hidden due to either display:none or visibility:hidden CSS properties.

How do you check if a div is hidden?

To check if an element is hidden or not, jQuery :hidden selector can be used. .toggle() function is used to toggle the visibility of an element.

Is hidden HTML?

An HTML hidden attribute indicates that the element is not yet or is no longer relevant. If something is marked as 'hidden' in the CSS, this makes the element hidden from search engines, making it impossible to display and invisible even to screen readers.

How do you know if an element is visible on screen?

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.


4 Answers

$(foo).is(":hidden")

can figure that out for you in current jQuery versions.

like image 86
Matti Virkkunen Avatar answered Sep 28 '22 21:09

Matti Virkkunen


You can just check if it's :hidden, for example:

$(".selector:hidden").length > 0
//or
$(".selector").is(":hidden")

This works if the parent is hidden, or any parent, or the element directly...as long as the element itself has no dimensions, it's :hidden.

like image 32
Nick Craver Avatar answered Sep 28 '22 20:09

Nick Craver


Like this:

alert($('#test1').is(":visible"));
#test {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test">
  <div id="test1">
    test
  </div>
</div>

View on JSFiddle

like image 35
treeface Avatar answered Sep 28 '22 20:09

treeface


jQuery uses offsetHeight. That works in most browsers. But you can check that without jQuery too.

like image 41
AutoSponge Avatar answered Sep 28 '22 22:09

AutoSponge