Jquery: if div is visible
Quickly check whether a div
is visible using the jQuery function .is(":visible")
:
This piece of code examines the CSS display and visibility properties, but it won't detect if the div is actually visible to the user on their screen.
Understanding :visible in jQuery
Visibility in the context of a webpage is determined by CSS properties such as display
, visibility
, opacity
, and the element's position in the viewport. jQuery's .is(':visible')
function checks if an element meets the criteria to be :visible
by CSS parameters, but it doesn't consider the element's position within the viewport.
Conditional checks and actions
You can take different actions based on whether a div
is visible or not. Observe the examples below:
SPA nuances: dynamically changing visibility
In single-page applications (SPAs), an element's visibility can change without a page reload due to dynamic loading. It becomes imperative to check the visibility again after page interactions or async updates. Here's a helpful utility function:
Non-obvious scenarios with :visible
The :visible
selector includes elements with a CSS property display
that is anything but none
, and visibility
of anything but hidden
. In an interesting turn of events, jQuery considers zero-sized elements invisible, even if technically displayed:
Hiding and showing: the game of peekaboo
To change an element's visible state, jQuery provides .hide()
and .show()
methods. Here's a basic guide:
Mastering visibility detection
Creating custom visibility functions
For more sophisticated scenarios, such as checking whether an element is in the viewport, you might need to add your own function to jQuery:
Caveats with hidden elements and .is(':visible')
A curious thing is that elements with an opacity
of 0 or those positioned off-screen are still considered :visible
according to jQuery:
Optimizing for performance
Using the :visible
selector can impact performance for large DOMs. For better performance, consider using specific selectors or limit the scope:
Was this article helpful?