Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery $ function syntax

What is the difference between the following function definitions?

1:

$(function () {
    //stuff here
}); 

2:

function($){
    //stuff here
}
like image 214
SilverLight Avatar asked Jun 02 '11 08:06

SilverLight


People also ask

What is the syntax of jQuery?

The jQuery syntax is tailor-made for selecting HTML elements and performing some action on the element(s). Examples: $(this). hide() - hides the current element.

What is $( function () in jQuery?

A function of that nature can be called at any time, anywhere. jQuery (a library built on Javascript) has built in functions that generally required the DOM to be fully rendered before being called. The syntax for when this is completed is: $(document). ready(function() { });

How do you create a function in jQuery?

Answer: Use the syntax $. fn. myFunction=function(){} The syntax for defining a function in jQuery is little bit different from the JavaScript.

What will the jQuery code $( P hide (); do?

jQuery hide() Method The hide() method hides the selected elements. Tip: This is similar to the CSS property display:none. Note: Hidden elements will not be displayed at all (no longer affects the layout of the page).


1 Answers

In #1, your function will be called by jQuery when the DOM is ready; passing a function into $() is a shortcut for $(document).ready(function() { ... }); (details here).

In #2, you're defining a function but neither calling it nor asking jQuery to call it. (And in fact, as shown, it's a syntax error — you'd need to be assigning it to something or calling it for it to be valid without a name.) Nothing you've quoted will execute the function, you'd have to call it yourself.

On #2, the idiom you've probably seen there is:

(function($) {
    // ...code using `$` for jQuery here...
})(jQuery);

That's fairly standard thing you'd do when you want the code to run immediately (not wait for DOM ready), and you want to use $ within the function to refer to jQuery, but you want to be compatible with noConflict mode. You see this a lot in plug-ins. It defines a function accepting a $ argument, which shadows any $ defined globally, and then immediately calls that function passing in jQuery as the argument. So even if $ doesn't map to jQuery globally, it does within that function. You can do the same thing like this:

(function() {
    var $ = jQuery;
    // ...code using `$` for jQuery here...
})();

...but for some reason the earlier example is more common, even if a bit less clear. (It's a couple of characters shorter, I suppose.)

like image 132
T.J. Crowder Avatar answered Oct 02 '22 08:10

T.J. Crowder