Skip to content

Instantly share code, notes, and snippets.

@jaydson
Created November 11, 2011 18:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaydson/1358813 to your computer and use it in GitHub Desktop.
Save jaydson/1358813 to your computer and use it in GitHub Desktop.
How to observe when an element is created
var readyElement = (function(){
return {
observe : function(id,callback){
var interval = setInterval(function(){
if(document.getElementById(id)){
callback(document.getElementById(id));
clearInterval(interval);
}
},60);
}
}
})();
readyElement.observe('my_awesome_new_element',function(el){ console.log(el) });
@felipecsl
Copy link

You can also use the DOM event DOMNodeInserted (https://developer.mozilla.org/en/DOM/DOM_event_reference) or, if using jQuery, livequery (http://docs.jquery.com/Plugins/livequery)

@jaydson
Copy link
Author

jaydson commented Nov 11, 2011

Yep. But i'm trying to create an hybrid solution, without any dependencies, like jQuery. But sure, live() method is very useful.
DOMNodeInserted is great, but just for modern browsers, right?
Well, the best solution is to use DOMNodeInserted, and fallback for something like the code above.
Thanks for comment.

@felipecsl
Copy link

Yeah the event is still a draft. I'd do the fallback thing as well. If you want to be more flexible, you can add options for the interval time and input selector format (id, class, element name, etc.) :)

@jaydson
Copy link
Author

jaydson commented Nov 11, 2011

Cool, sounds like a good micro-solution.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment