0

In this example someone shows a jQuery onclick event. My shows this:

$(function() {
    $('.post').on('click', function() {
        SOME STUFF
    });
});

But what are the first and last line doing? if i remove the lines, it's not working:

$('.post').on('click', function() {
    SOME STUFF
});

But why? In the linked example is a second commenter. He shows this way (without first/last line).

Can someone explain this?

Community
  • 1
  • 1
fechnert
  • 1,215
  • 2
  • 12
  • 30
  • possible duplicate of [What does $(function() {} ); do?](http://stackoverflow.com/questions/7642442/what-does-function-do) – Bergi Apr 29 '14 at 09:24

4 Answers4

3

It is a shortcut for $( document ).ready(...)

See http://api.jquery.com/ready/

Quoting the doc :

While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code. [...]

All three of the following syntaxes are equivalent:
* $( document ).ready( handler )
* $().ready( handler ) (this is not recommended)
* $( handler )

LeGEC
  • 46,477
  • 5
  • 57
  • 104
3

That is short for document.ready. It waits until the entire document is loaded and the element with class .post can be found and bound to.

If you omit that part, the jQuery function will not find the element and your event will not work.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
0

The first and last lines create an anonymous function. In computer programming, an anonymous function is a function defined, and possibly called, without being bound to an identifier.

In the example here it is used to set the event listener that is loaded onload of the page.

$(function() {
    $('.something').on('click', function() {
        alert('hello');
        $(this).addClass('classOne');
    });
});
Dean Meehan
  • 2,511
  • 22
  • 36
0
$(function(){}); 

is jQuery short hand for

$(document).ready(function() {});

which ensures your document is ready for manipulation before executing anything within it. In many ways its similar to the browser window.onready event. See jQuery docs..

The risk if you don't wrap your jQuery code in either of these forms of the functions is that you will try and manipulate elements before they have been created by the browser. Your code is not guaranteed to fail, but you could, at the very least, get inconsistent behaviour.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
Steve Mc
  • 3,433
  • 26
  • 35