We can use jQuery to check if an element is visible in the HTML by using the is() method along with the :visible selector.
if ($("#div1").is(":visible")) {
//The Element is visible
} else {
//The Element is NOT visible
}
Let’s take a look at a simple example below.
Let’s say we have the following HTML:
This text is currently visible
If we want to check if the paragraph in #div1 is visible, we can use the is() method along with the :visible selector inside of an if else conditional statement.
if ($("#div1 p").is(":visible")) {
//#p1 is visible
} else {
//#p1 is NOT visible
}
If you are using WordPress, don’t forget to change the $ to jQuery as below:
if (jQuery("#div1 p").is(":visible")) {
//#p1 is visible
} else {
//#p1 is NOT visible
}
Let’s see this in action in the example below.
Using jQuery to Check if an Element is Visible with a Click
In this example, we will have a div with a greenish background. We will provide a button for the user to use to show/hide the div using jQuery. We will also provide a button for the user to check the visibility of the div.
Here is the HTML code:
Hide/Show box above
Check visibility
We can make the #click-me1 button show or hide the div using jQuery.
The button #click-me2 will allow the user to check the visibility of the div after we show/hide it. We will do this using the is() method along with the :visible selector
Finally, we will show the result of whether the div is visible or not using the text() method.
Here is the JavaScript code:
$("#click-me1").click(function(){
//Show/hide div
$("#div2").toggle();
});
$("#click-me2").click(function(){
if ($("#div2").is(":visible")) {
$('#results').text('The box above IS visible.');
} else {
$('#results').text('The box above is NOT visible.');
}
});
The final code and output for this example of using jQuery to check if a div is visible is below:
Code Output:
Full Code:
Hide/Show box above
Check visibility
<script>
$("#click-me1").click(function(){
$("#div2").toggle();
});
$("#click-me2").click(function(){
if ($("#div2").is(":visible")) {
$('#results').text('The box above IS visible.');
} else {
$('#results').text('The box above is NOT visible.');
}
});
</script>
Hopefully this article has been useful for you to understand how to use jQuery to check if an element is visible.