I came across a piece of code which looks like this:
jQuery(function($) {
$('#saySomething').click(function() {
alert('something');
});
});
I don’t quite get it. Why can’t I simply do this:
$('#saySomething').click(function() {
alert('saySomething');
});
is the shorthand version of:
If you don’t wait for the
documentto be ready, the elements that you’d bind events on won’t exist in the dom, and the events wont actually be bound.Alternatively you could wait for the
bodyto have finished loading, however that will include waiting for images, which take longer to load.Truth be told, you don’t have to wait for
document.ready. You can go ahead and use$('#saySomething').click(...)if you know the element exists in the DOM:There is one last nuance to
jQuery(function ($) {...});that you should know about. The$parameter in the function is used to aliasjQueryto$, which will allow you to use the$shorthand within the function without having to worry about conflicts with other libraries (such as prototype).If you’re not waiting for
document.readyit’s common to see an IIFE used to alias jQuery: