Bind ready event to create javascript dom element

I would like to know if we can associate a loaded or finished event with the element created by the script when loading dom. I heard from live (), but this is not something clickable, it is just an item to be downloaded.

Thanks for your help!

+4
source share
3 answers

I think your best shot is the load event.

 $('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); 
+2
source

If you want to separate code snippets to create an element and handle loading events, you can try to have your dynamically created element fire a custom event in the window:

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

With the pointer back to itself in the additional parameters, you can have a separate handler setting in jQuery (document) .ready to look for the window event "myElementInit" and grab the link to the element from the additional parameters:

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

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

Delegated events have the advantage that they can handle events from descendant elements that will be added to the document later. By choosing an element that is guaranteed to be present during the delegated event handler, you can use delegated events to avoid frequently connecting and removing event handlers. This element can be an element of the presentation container in the Model-View-Controller, for example, or document , if the event handler wants to control all the bubble events in the document. The document element is available at the beginning of the document before loading any other HTML code, so it is safe to attach events there without waiting for the document to be ready.

0
source

All Articles