DEV Community

Cover image for Waiting for visible element
John Kapantzakis
John Kapantzakis

Posted on • Edited on

4

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:

function waitVisible(elem, callback, timeout) {
let timer = setInterval(() => {
if (elementVisible(elem)) {
callback();
clearInterval(timer);
timer = null;
}
}, 10);
const tm = timeout || 5000;
setTimeout(() => {
if (timer) {
clearInterval(timer);
}
}, tm);
}
// JQuery implementation of $elem.is(':visible')
function elementVisible(elem) {
return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length );
}
view raw waitVisible.js hosted with ❤ by GitHub

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);
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!

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)