I want to call a function after an element has been created. Is there a way to do this?
Example:
$("#myElement").ready(function() { // call the function after the element has been loaded here console.log("I have been loaded!"); });
How are you creating the element?
If you're creating it in the static HTML then just use .ready(handler)
or .on("load", handler)
. If you're using AJAX though that's another kettle of fish.
If you're using jQuery's load()
function then there's 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:
$.ajax({ url: 'somepage.html', success: function(){ //callback } });
If you're just creating the element and appending it like this:
$('body').append('<div></div>');
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'); $('#mydiv').css({backgroundColor:'red'});
But acctually, saying THAT you could just do this:
$('<div />', {id:'mydiv'}).appendTo('body').css({backgroundColor:'red'});
You may want to look into jQuery live events. You attach an event handler to a selector that either matches now or after additional elements are created in your DOM.
So if you have a <ul>
and you dynamically create new <li>
items, in your $(document).ready()
you can wire up a selector to an event handler so that all of your <li>
elements will be wired for that event.
Here's a jsFiddle sample that demos live
.
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With