Since in jQuery it is possible to change the visibility of an element, how can I know if an element is visible or not at run time?
Since in jQuery it is possible to change the visibility of an element, how can I know if an element is visible or not at run time?
It is true that you can use is(":visible")
but from experience I recommend you use classes so that you do not have problems when testing your applications, since many test libraries do not have the components that are visible and tested for a long time. that your component does hide()
or show()
jQuery will continue indicating that it is not visible, and the behavior of your components will be strange. This has happened to me with the QUnit test library, from the jQuery authors.
What I would do would be: $el.toggleClass("hide")
or $el.addClass("hide")
.
And check it with: !$el.hasClass("hide")
.
Also be careful when using is(":visible")
because visibility: hidden
u opacity: 0
are considered visible since they occupy space in the layout.
Keep in mind that my solution is to check if only the element is visible. It may be the case that one of the parents is not visible and therefore can not be seen. If you want to check something like that maybe it's better that you use is(":visible")
or !$(..).closest(".hide")
.
Just as jquery uses the :visible
selector in your example , you can incorporate it into the same search expression of the element
var visible = $("#element:visible").length > 0;
or filtering
var visible = $("#element").filter(":visible").length > 0;
These forms of element filtering are particularly useful when you are going to iterate over a list of results
$(".elemento:visible").each(function() {
...
}
Although if you only need a Boolean answer, as you have written Carlos Muñoz , you can do it like this
var isVisible = $("#elemento").is(":visible");
I was involved in this specific case where the initial solution would suffice with:
if ($elementoDOM.is(':visible')){ console.log('el elemento está visible') }
BUT! a lot of eye that as a partner said in other comments this does not apply to elements that have the property: opacity:0
.
Personally the most used is with opacity
since in such a way it is possible to animate the appearance / disappearance of elements in the DOM in an aesthetic way. Reason why the precise instruction that just worked for me is:
if ($elementoDOM.css('opacity')==1) { ... } ó
if ($elementoDOM.css('opacity')==0) { ... }
Be careful not to put the number (0,1) in double or single quotes!
Greetings.
You can use the following
if($('#elemento').css('display') == 'none'){
// Acción si el elemento no es visible
}else{
// Acción si el elemento es visible
}
in the case that we also want to check opacity we do:
if($('#elemento').css('display') == 'none' || $('#elemento').css('opacity') == 0){
// Acción si el elemento no es visible
}else{
// Acción si el elemento es visible
}