Javascript tip of the day – jQuery document ready shortcuts
24/09/2011
Everyone who has used jQuery for longer than a few minutes is probably aware of the document ready function:
$(document).ready(function(){
// do something
});
By wrapping your code up like that you guarantee that any html elements you need to reference have actually been created and are ready for manipulation. Simple enough, but there's actually an even simpler way of doing the same thing:
$(function(){
// this works exactly the same
});
Handy eh? Also, because all you're really doing is passing in a function, it doesn't have to be anonymous like in the above examples. Try passing in a reference to an existing function:
function startup() {
// do stuff
}
$(startup);
The startup function will then be called on document ready, but could also be called separately if needed.