• Home
  • About
  • Resume

Implement “onVisible” event for HTML DOM element in JavaScript

By , 02/06/2013 2:56 PM

Well, not exactly, but method described in this particular scenario can be expanded to other cases. Imagine you have a clickable element, let’s say a SPAN and when user clicks this element – it is covered by an absolutely positioned DIV with a higher z-index. In other words a dialog is displayed:

<span onclick="showDialogDiv()">Click here</span>

When user closes the dialog – your SPAN needs to detect this event, to perform some functions (refresh data on the page etc.) but you have no control over function that closes the DIV, so you can’t hook into it. All you know is that DIV’s display style is set to “none” when this happens. It would be cool if there was an “onvisible” event so you could do something like

<span onclick="showDialogDiv()" onvisible="performAction()">Click here</span>

but there’s no such event, so we need to simulate it. Which is surprisingly easy:

<span onclick="showDialogDiv(); var i=setInterval(function(){if ($('xdivDialog').style.display=="none") {clearInterval(i);performAction()}},1000)">Click here</span>

Basically when user clicks the SPAN to show the dialog – at the same time a timer is started that regularly checks visibility of the dialog DIV (whether it’s style display became “none” again). Once this is detected, that means opener SPAN is visible again – timer is stopped and function to handle event is called.

Leave a Reply

Panorama Theme by Themocracy