Dennis Martinez Dennis Martinez - 1 year ago 62
jQuery Question

How can I call a function after an element has been created in jquery?

I want to call a function after an element has been created. Is there a way to do this?


$("#myElement").ready(function() {
// call the function after the element has been loaded here
console.log("I have been loaded!");

Answer Source

How are you creating the element?

If you're creating it in the static HTML then just use .ready() or .load(). If you're using ajax though that's another kettle of fish.

If you're using jquery's load() function then theres a callback you can run when the contents been loaded:

$('#element').load('sompage.html', function(){ /* callback */ });

If you're using jquery's $.ajax or $.get, $.post functions then there's a success callback in that:

  url: 'somepage.html',
  success: function(){

If you're just creating the element and appending it like this:


Then you can do this instead:

$('<div />', { id: 'mydiv' }).appendTo('body').ready(function(){ /* callback */ });

But this won't matter - because it's synchronous (which means that the next line of code won't run until it's added the element to the DOM anyway... - unless you're loading images and such) so you can just do:

$('<div />', { id: 'mydiv' }).appendTo('body');

But acctually, saying THAT you could just do this:

$('<div />', {id:'mydiv'}).appendTo('body').css({backgroundColor:'red'});