Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to check if a div is visible using jQuery?
You can use .is(':visible') to check if a div element is visible. This jQuery selector returns true if the element is currently visible on the page, and false if it's hidden through CSS properties like display: none, visibility: hidden, or if its width and height are set to zero.
Example
The following example demonstrates how to check if a div is visible and show it if it's hidden −
<!DOCTYPE html>
<html>
<head>
<title>Check Div Visibility with jQuery</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#checkBtn").click(function() {
var isVisible = $('#div1').is(":visible");
if (isVisible == false) {
$('#div1').css({"display": "block", "color": "red"});
$("#status").text("Div was hidden, now showing it!");
} else {
$("#status").text("Div is already visible!");
}
});
$("#toggleBtn").click(function() {
$('#div1').toggle();
});
});
</script>
</head>
<body>
<div id="div1" style="display:none; padding: 10px; background-color: lightblue;">
<p>This div is now visible!</p>
</div>
<button type="button" id="checkBtn">Check and Show Div</button>
<button type="button" id="toggleBtn">Toggle Div</button>
<p id="status" style="margin-top: 10px; font-weight: bold;"></p>
</body>
</html>
Alternative Methods
You can also use other methods to check visibility −
// Check if hidden
if ($('#div1').is(':hidden')) {
console.log('Div is hidden');
}
// Check CSS display property directly
if ($('#div1').css('display') === 'none') {
console.log('Div has display: none');
}
// Check visibility property
if ($('#div1').css('visibility') === 'hidden') {
console.log('Div has visibility: hidden');
}
The :visible selector is the most comprehensive method as it considers all factors that can make an element invisible, including display, visibility, opacity, and dimensions.
Advertisements
