What is the difference between the following function definitions?
1:
$(function () {
//stuff here
});
2:
function($){
//stuff here
}
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.
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() { });
Answer: Use the syntax $. fn. myFunction=function(){} The syntax for defining a function in jQuery is little bit different from the JavaScript.
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).
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With