Function to check if elements are "visible"?

I workin on a custom “app” (plugin, basically) with the frappe framework.

Basically the plugin will allow users to place an element with the id=“gtMap” and then a javascript script will initialize a Google Map inside that element based on the location fields inside the record.

Since it’s not efficient or economical (the API calls to load the map aren’t free) to fire the map javascript function on every single page load. I’d like to only call the initMap function if the element “gtMap” is visible.

Now, “visible” can mean multiple things, of course. For instance, it could be inside a collapsible tab, or the user could place the map element inside a modal/popup. Since the app is designed to give the user/developer the freedom to place the map wherever they want, I don’t have control over how the user hides/unhides the element.

Is there a univeral method to check if an element is in the DOM and visible (as in, visible to the user’s eyes; it’s not being hidden behind something)?

You can use Intersection Observer to check if an element is in the visible viewport and has allocated space.

An element with visibility:hidden or opacity: 0 have space allocated so will be deemed visible. You can check for those using checkVisibility.

2 Likes

note that any method used will have the same foibles - a box with 1 pixel in the corner of the viewport is “visible”, even if the box is 1000x1000.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.