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?
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.
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.
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.
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.
$(foo).is(":hidden")
can figure that out for you in current jQuery versions.
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 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
jQuery uses offsetHeight. That works in most browsers. But you can check that without jQuery too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With