loading...
Cover image for Waiting for visible element

Waiting for visible element

kapantzak profile image John Kapantzakis Updated on ・2 min read

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.

google.charts.setOnLoadCallback(drawChart);

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!

Posted on Aug 19 '19 by:

kapantzak profile

John Kapantzakis

@kapantzak

Web developer - want to learn something new every day

Discussion

markdown guide