To check whether an element is visible or hidden in jQuery, use $(selector).is(":visible") or $(selector).is(":hidden"). In jQuery, an element is considered hidden if it has display: none, is inside a hidden ancestor, has zero width and height (0px box dimensions), or is a <input type="hidden">.
1. Checking Visibility with :visible and :hidden
Query the target element and call .is(":visible") or .is(":hidden") to get a boolean result:
<div id="status-banner" style="display: none;">Saved changes</div>
<button type="button" id="toggle-banner">Toggle Banner</button>
<script>
const $banner = $("#status-banner");
// Returns false when #status-banner has display: none
console.log("Is visible:", $banner.is(":visible"));
// Returns true when #status-banner is hidden
console.log("Is hidden:", $banner.is(":hidden"));
$("#toggle-banner").on("click", function () {
$banner.toggle();
console.log("Now visible:", $banner.is(":visible"));
});
</script>
2. How jQuery Defines :hidden vs. visibility: hidden and opacity: 0
jQuery’s :hidden selector checks layout box presence and display: none, which differs from CSS visibility: hidden or opacity: 0:
-
Elements treated as
:hiddenby jQuery:display: noneon the element or an ancestor,<input type="hidden">, or elements whose width and height are both0(such as an unrendered/collapsed container). -
Elements treated as
:visibleby jQuery: Elements taking up layout space (width > 0orheight > 0) even ifvisibility: hiddenoropacity: 0makes them visually invisible—check.("visibility")or.("opacity")explicitly when layout space is still occupied.const $card = $(“.modal-card”); const isInLayout = $card.is(“:visible”); const isVisuallyOpaque = isInLayout && $card.css(“visibility”) !== “hidden” && Number($card.css(“opacity”)) > 0;
console.log(“In layout:”, isInLayout, “Visually opaque:”, isVisuallyOpaque);
3. Common Traps to Avoid
- Using
if ($("#el"))to test visibility: A jQuery object is always truthy even whenis hidden or does not exist in the DOM—always check.is(":visible"),.is(":hidden"), or.length. - Assuming
:visiblemeansopacity > 0orvisibility !== "hidden": An element withvisibility: hiddenoropacity: 0still occupies layout space, so$(el).is(":visible")returnstrue. * Checking visibility during mid-animation transitions: Calling.is(":visible")while.fadeOut()or.slideUp()is still running reflects the live layout state at that exact frame rather than the final post-animation state. — TL;DR: Use$(selector).is(":visible")or$(selector).is(":hidden")to check layout visibility in jQuery, remember thatvisibility: hiddenandopacity: 0still count as:visiblebecause layout space remains, and never rely on truthiness of a jQuery wrapper (if ($el)).
Are you checking toggles/modals controlled by .show()/.hide()/.toggle(), dealing with visibility: hidden or opacity: 0, or checking visibility after an animation finishes?
