DEV Community

Cover image for Waiting for visible element
John Kapantzakis
John Kapantzakis

Posted on • Updated on

Waiting for visible element

Sometimes we need to call a function when a specific element is visible.

We might want to load something that is going to calculate its dimensions based on its parent element's dimensions.

I, my self, have been in this position, trying to trigger a plugin init function when a specific area is visible (or, better, when this area has dimensions).

This is a solution I've came up with:

The waitVisible function will call a given function, as soon as the specified element gets visible.

It takes 3 arguments:

  • The element we want to check upon
  • The callback function that we want to be executed when the element gets visible
  • The maximum amount of time that the function is going to check for the element's visibility (default: 5000 ms)

Example (Google charts)

Let say that we want to display a pie chart (example here) inside a div that is not initially visible.

First, we call the drawChart function as soon as the Google charts script loads.

Enter fullscreen mode Exit fullscreen mode

If you check the Result tab on the fiddle below, you can see that the chart is placed on the left side (when viewing in a relatively wide screen), taking as little space as it can in order to be displayed.

Here, we use waitVisible to call the drawChart function. The drawChart is able to calculate its parent eleemnt's dimensions and the chart takes up all the available width as you can see in the next fiddle:

That's my solution to this problem. If you want to propose something else, please feel free to comment!

Top comments (0)