Skip to content

Instantly share code, notes, and snippets.

@jaydson
Created November 11, 2011 18:36
Show Gist options
  • Select an option

  • Save jaydson/1358813 to your computer and use it in GitHub Desktop.

Select an option

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
Copy Markdown

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

jaydson commented Nov 11, 2011

Copy link
Copy Markdown
Author

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
Copy Markdown

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

jaydson commented Nov 11, 2011

Copy link
Copy Markdown
Author

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