-2

What is the difference between

$(function()
{
    $(".some").click(function()
    {
        ...
    });
});

and

$(".some").click(function()
{
    ...
});

I know from here that $(function() is shorthand for $(document).ready(function(). But why are we waiting for the document to be ready? Will the function not be only called when some is clicked anyway?

Note: #2 does not work in my case.

Jeroen
  • 60,696
  • 40
  • 206
  • 339
Hele
  • 1,558
  • 4
  • 23
  • 39

4 Answers4

6

The difference is that #1 waits for the DOM to fully load before running the JavaScript. The second code runs the JavaScript when it receives it which means it looks for .class elements before they have finished loading. This is why it doesn't work.

Craicerjack
  • 6,203
  • 2
  • 31
  • 39
  • 1
    As a side note, document pseudo ready event isn't necessary if you bind event after targeted element is available in DOM – A. Wolff Aug 17 '15 at 11:14
3

You need the document to be ready, i.e. all elements of the document to be available, before you can add an event listener to an element.

The reason is: consider a button, and you want an event listener (listening for the click event, for example.

When your sript runs but the button is not yet present, the attempt to attach the listener will fail. As a result, the associated function cannot be called once the button is actually clicked.

Does that answer your question?

Burki
  • 1,188
  • 19
  • 28
0

You use the $(function()) simply because you need the DOM to fully load.

For example you have a button and you want to add some action on click. You click the button, but nothing happened, because the button was handled prior to the DOM loading.

If you won't check that the DOM is fully loaded, some unexpected behavior might occur.

Please do not confuse between onload() to ready(), as on load executes once the page is loaded and ready() executes only when the DOCUMENT is fully ready.

Barr J
  • 10,636
  • 1
  • 28
  • 46
-1

$(function(){...}) triggers the function when the DOM is load, it's similar to window.onload but part of jquery lib.

you can also use $(NAMEOFFUNCTION);

It's there to be sure the event has a element to listen to.

PRDeving
  • 679
  • 3
  • 11
  • Not completely true, $(function(){...}) is running when the page is ready. jQuery gives different the meaning to read and load. Take a look here to get better details https://learn.jquery.com/using-jquery-core/document-ready – Angelo Badellino Aug 17 '15 at 11:00