How to check element visible or hidden using jQuery

Below is a simple piece of jQuery code which checks the visibility of element using jQuery. jQuery provides "visible" selector which can be used to check the visibility.

Earlier I had posted about How to check if element is empty, Difference between empty() vs remove() and Don't use jQuery.size() to count number of element. And in this post, find jQuery way to check element visible or hidden.

var isVisible = $('#dvData').is(':visible');
alert("dvData is " + isVisible);

If you want to check if element is hidden, then you can use ":hidden" selector.

var isHidden  = $('#dvData').is(':hidden');
alert("dvData is " + isHidden);

There is a myth that ":visible" and ":hidden" selector checks for "display" css property which is used to show/hide the element. But this is not correct.

<div id="dvData" style="display:none;">
//Your content goes here...
</div>

Before jQuery 1.3.1 (and older) an element was visible if its CSS "display" was not "none", its CSS "visibility" was not "hidden", and its type (if it was an input) was not "hidden" But After jQuery 1.3.1 versions an element is visible if its browser-reported offsetWidth or offsetHeight is greater than 0.

However, if you have used "visibility" css property to hide the element then ":visible" and ":hidden" selector will not work. Elements with visibility: hidden or opacity: 0 are considered to be visible, since they still consume space in the layout.

So if you have seen the above demo then it must be clear to you that ":visible" and ":hidden" selector will not work with css property "visibility". So what's the solution?

If you have used "visibility" css property to hide the element then use ":hidden" jQuery selector to check the visibility.

<div id="dvData" style="visibility:hidden;">
//Your content goes here...
</div>

then use below code to find out where element is visible or not.

if ($('#dvData').css("visibility") == "hidden")
{
   // Item is hidden. Write your code.
}
else
{
   // Item is Visible. Write your code.
}

Read "What's the difference between display: none and visibility: hidden?"

Feel free to contact me for any help related to jQuery, I will gladly help you.



Responsive Menu
Add more content here...