Rozkalns
Rozkalns

Reputation: 512

Jquery function, missunderstanding. Explanation needed

I've seen very much tutorials, where in the demo I see something like this:

// my dummy example
$(function() {
    $('a.change').bind('click',function(event){
        $('body').css('background','#27272')
    });
});

I do not understand what $(function() { is doing and why it is not working? What can i do to get it working properly without breaking other code?

Upvotes: 0

Views: 62

Answers (4)

mingos
mingos

Reputation: 24502

OK, I think you're confused about anonymous functions. An anonymous function - just like any other, only without a name. It's created usually as an argument to another function:

$('body').fadeIn('1000',function() {
    alert('yay!');
});

It is intended for one-time use (so no use for a function name).

I suspect it's not working for you because it's not passed as a valid argument. The $, which I suspect is the jQuery object, usually requires another jQuery object or a string as parametre, not an anonymous function (unless it returns something meaningful). However, the parametre to bind is created OK.

Now, what you might have wanted to do is to create a self-calling anonymous function. In this case, the syntax might also be:

(function($) {
    $('a.change').bind('click',function(event){
        $('body').css('background','#27272')
    });
})(jQuery);

This creates an anonymous function and then executes it (parentheses with an argument at the very end).

[EDIT]

Oh, I'm sorry to have offered a misleading piece of info, let me clarify: the syntax you used is valid as well, as the jQuery object will execute the function contained in it (callback) after loading the DOM. So it's actually valid syntax.

Upvotes: 1

kannix
kannix

Reputation: 5157

$(function() {}) is a shortcode for $(document).ready(handler) more info can be found here

Your posted code shouldn't break anything. Maybe you can provide a jsfiddle where we can look into it.

Upvotes: 4

BiAiB
BiAiB

Reputation: 14122

it is documented here on the official documentation : http://api.jquery.com/jQuery/#jQuery3

jQuery( callback ) The function to execute when the DOM is ready.

so, basically, the callback function will be called once the DOM is loaded and ready to be messed up. If you weren't using it, the nodes may not be available, especially in scripts on the top of the HTML tree.

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337560

$(function() { is a shortcut for: $(document).ready(function() { ... });. The latter version is a bit more readable. It means that the code you put between the braces will be executed when the document object fires it's ready event.

The only real reason this would break anything is if you have put this code in your page without first including jquery.js, or you have put it in the wrong place.

Upvotes: 3

Related Questions