Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQUERY $(function() { initialisation

Tags:

jquery

I've been working with JQuery for some time now and I've always used the following to initalise my javascript:

$(document).ready( function() {
// Initalisation logic
});

However, recently I've noticed a lot of examples using the following:

$(function() {

});

Whats the difference?

Thanks

like image 443
Mantisimo Avatar asked Jan 22 '11 13:01

Mantisimo


People also ask

What is jQuery $( function?

The jQuery syntax is tailor-made for selecting HTML elements and performing some action on the element(s). Basic syntax is: $(selector).action() A $ sign to define/access jQuery. A (selector) to "query (or find)" HTML elements.

What does $( document .ready function () mean?

$( document ).ready()A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.

How do you call a function in document ready jQuery?

jQuery Document Ready Example $(document). ready(function() { //DOM manipulation code }); You call jQuery's $ function, passing to it the document object. The $ function returns an enhanced version of the document object.

What is init function in jQuery?

$( init ); The init() function itself uses jQuery to fade all h1 headings in the Web page out, then in. Take a look at the first line of the function: $('h1').


2 Answers

Basically, there isn't one. The $(...) format is a shortcut. See the API docs for jQuery() for details.

I like to use it like this:

jQuery(function($) {
    // ...all of my jQuery-specific code here...
});

...because then if I need to, I can use noConflict if I end up having to mix something into the page that also wants the $ symbol, but I can still use $ in my code (because jQuery passes itself into the callback as the first argument, and as you can see I'm accepting that argument as $ in my callback function — and so that shadows any global $ symbol that another library might be using). The above also has the advantage that I can have symbols global to my code (vars within the anonymous function) that are not actually globals.

like image 64
T.J. Crowder Avatar answered Oct 24 '22 23:10

T.J. Crowder


The difference is a matter of style. One is just a shortcut of the other. :) See http://api.jquery.com/jQuery/ near the bottom where it says "Executes the function when the DOM is ready to be used"

When I asked one of the jQuery UI people what they preferred, he said he preferred the more verbose way. However, people in my shop use this version:

$(function() {

});
like image 25
finneycanhelp Avatar answered Oct 24 '22 22:10

finneycanhelp