In jQuery and css, We hide and show the visibility of the element.We can use the functions .hide(), .show() or .toggle() or we can do it using css function also.
Question is how would we test if an element is visible or hidden using jQuery?
In jQuery, We can use is() with :hidden or :visible selector
1 2 | var isVisible = $('#myDiv').is(':visible'); var isHidden = $('#myDiv').is(':hidden'); |
OR
1 2 3 4 | if($('#myDiv').is(':visible')) { // do something here } |
The :visible selector according to the jQuery documentation:
1. They have a CSS display value of none.
2. They are form elements with type=”hidden”.
3. Their width and height are explicitly set to 0.
4. An ancestor element is hidden, so the element is not shown on the page.
5. Elements with visibility: hidden or opacity: 0 are considered to be visible, since they still consume space in the layout.
This is useful in some cases and useless in others, because if you want to check if the element is visible (display != none), ignoring the parents visibility, you will find that doing .css(“display”) == ‘none’ is not only faster, but will also return the visibility check correctly.
If we want to check visibility instead of display, we should use: .css(“visibility”) == “hidden”.
In jQuery, We can use hidden and visible selector to test the element’s visibility.
hidden selector
1 2 | // Matches all elements that are hidden $('element:hidden') |
And the visible selector:
1 2 | // Matches all elements that are visible $('element:visible') |