views:

55

answers:

2

Hi there, 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!

+2  A: 

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);
jAndy
Problem is that i can't edit the parent item.
Artusamak
A: 

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 = $('', { 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; ... } );

JJ Blumenfeld
As said before my problem is that i can't edit the parent item.
Artusamak
not sure I understand then. can you post some code snippet? what did you mean "I heard from live()"?
JJ Blumenfeld
I can't post some code.1/ I've got a script that i can't modify adding a div in the dom when the document is ready.2/ I've got my script which is adding an other div in the dom and which need to be created after the div created in 1/ has been really added to the DOMIs that much clear?
Artusamak