Artusamak
Artusamak

Reputation: 61

Bind ready event on javascript dom element creation

i would like to know if we can bind a loaded or ready event on an item created by a script when the dom is loaded. I heard from live() but it's not something clickable, it's just an item which has to load.

Thanks for your help!

Upvotes: 6

Views: 7322

Answers (3)

Sorin Comanescu
Sorin Comanescu

Reputation: 4867

You can use the delegated form of the .on() event, as documented here:

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.

Upvotes: 0

JJ Blumenfeld
JJ Blumenfeld

Reputation: 13

If you want to be able to separate the pieces of code for creating the item and the load event handling you could try having your dynamically created element trigger a custom event on the window:

var myElement = $('<img/>', {
   src:   '/images/myimage.png'
}).appendTo(document.body);

$(window).trigger( {type: "myElementInit", myObject : myElement} );

With a pointer back to itself in the extra parameters, you could then have a separate handler set-up within a jQuery(document).ready to look for the "myElementInit" window event and grab the reference to the element out of the extra parameters:

jQuery.('window').bind( "myElementInit", function(event){
  var theElement = event.myObject;
...
} );

Upvotes: 0

jAndy
jAndy

Reputation: 236032

I guess your best shot is the load event there.

$('element').load(function(){
   alert('loaded');
});

native

var elem = document.getElementById('element_id');
elem.onload = function(){
   alert('loaded');
};

Another example for dynamic creation:

$('<img/>', {
   src:   '/images/myimage.png',
   load:  function(){
     alert('image loaded');
   }
}).appendTo(document.body);

Upvotes: 2

Related Questions