views:

38

answers:

3

Can I create an event so I can execute some javascript whenever an element with a specific ID becomes visible or appears on the page?

The element comes from a remote resource (so isn't in MY html code but appears on page load) and I'd like some code to run when it appears (and only if it appears, it may not appear every load).

Thanks!

A: 

If a selector doesn't find a match, it just won't run, so just having code like this is fine:

 $("#elementID").each(function() {
   //do something
 });

Just run that statement in whatever code loads the ID, or alternatively rig it up in the ajax handler if that's how it's getting loaded like this:

$.ajaxSetup({
   complete: function() {
    $("#elementID").each(function() {
     //do something
    });
   }    
 });
Nick Craver
+1  A: 

You could use live() method:

$('div_id_or_class').live('click', function(){
 // ................
});
Sarfraz
`click` is not an event associated with something appearing or being loaded on the page.
Marko Dumic
@Marko: Thanks for that, made the correction. :)
Sarfraz
+1  A: 

You can make a function that will check every X milliseconds if such element appeared on the page (a plain Javascript solution):

(​function ()​ {
    var intervalId = window.setInterval(function() {
        if (null != document.getElementById('myDivId')) {
            // the div appeared on the page
            // ... do your stuff here:
            alert('its here!');

            // optionally stop checking (obviously it's there already 
            // unless you decide to remove it)
            window.clearInterval(intervalId);
        };
    }, 100); // perform check every 100 milliseconds
}​)()​;

There is the possibility that the DIV is there all the time, only not visible. So your checking function should be a little different:

var el = document.getElementById('myDivId');
if (null != el && (el.offsetWidth > 0 || el.offsetHeight > 0)) {

Basically (el.offsetWidth > 0 || el.offsetHeight > 0) indicates that element is not hidden by its or its parents' CSS properties.

Marko Dumic
Fiddle with it here: http://jsfiddle.net/xS63J/
Marko Dumic
@Marko Dumic thanks, I'm curious how resource intensive it would be to be executing this every 100 milliseconds? I guess it would be unnoticable, but just to double check :)
AndyC
Unnoticeable, in my experience. Also, I made light by doing it natively, without jQuery etc.
Marko Dumic
@Marko Dumic This worked perfectly! Brilliant! Thanks!
AndyC