What Does $(Function() {} ); Do

What does $(function() {} ); do?

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

is just jQuery short-hand for

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

What it's designed to do (amongst other things) is ensure that your function is called once all the DOM elements of the page are ready to be used.

However, I don't think that's the problem you're having - can you clarify what you mean by 'Somehow, some functions are cannot be called and I have to call those function inside' ?
Maybe post some code to show what's not working as expected ?

Edit: Re-reading your question, it could be that your function is running before the page has finished loaded, and therefore won't execute properly; putting it in $(function) would indeed fix that!

What does $(function() {}) mean in javascript

It is document ready handler

$( document ).ready(function() {
// Handler for .ready() called.
});

This is to prevent any jQuery code from running before the document is finished loading (is ready).

is equivalent to

$(function() {
// Handler for .ready() called.
});

If .ready() is called after the DOM has been initialized, the new handler passed in will be executed immediately.

Here are some examples of actions that can fail if methods are run before the document is fully loaded:

1.Trying to hide an element that is not created yet

2.Trying to get the size of an image that is not loaded yet

The jQuery team has created an shorter method for the document ready event:

$(function(){

// jQuery methods go here...

});

It is depend upon the developers which syntax is to be used but document ready event is easier to understand when reading the code

For more details : See

Meaning of (function(){ in Javascript

The first example is a closure, it's a design pattern commonly used in JavaScript. In the second one you're calling the $ function giving another function as parameter (jQuery will execute it as soon as the document is ready, since it's an alias of $(document).ready(function () {})).

This is an example of closure:

(function () {
var foo = 'foo';
var bar = 'bar';
window.foo = foo;
})(); // Those () mean that you're calling this anonymous function

console.log(typeof foo); // Logs 'string'
console.log(typeof bar); // Logs 'undefined', since 'bar' is internal to the closure's
// scope and was not exposed like was 'foo'

And this is an example of $(function () {}):

$(function () {
alert('Document ready');
});

Check these pages:

  • How do JavaScript closures work?
  • https://api.jquery.com/jquery/#jQuery3

What does (function($) {})(jQuery); mean?

Firstly, a code block that looks like (function(){})() is merely a function that is executed in place. Let's break it down a little.

1. (
2. function(){}
3. )
4. ()

Line 2 is a plain function, wrapped in parenthesis to tell the runtime to return the function to the parent scope, once it's returned the function is executed using line 4, maybe reading through these steps will help

1. function(){ .. }
2. (1)
3. 2()

You can see that 1 is the declaration, 2 is returning the function and 3 is just executing the function.

An example of how it would be used.

(function(doc){

doc.location = '/';

})(document);//This is passed into the function above

As for the other questions about the plugins:

Type 1: This is not a actually a plugin, it's an object passed as a function, as plugins tend to be functions.

Type 2: This is again not a plugin as it does not extend the $.fn object. It's just an extenstion of the jQuery core, although the outcome is the same. This is if you want to add traversing functions such as toArray and so on.

Type 3: This is the best method to add a plugin, the extended prototype of jQuery takes an object holding your plugin name and function and adds it to the plugin library for you.

jQuery $(function() {}) vs (function () {})($)

As you mentioned, the former is indeed a shorthand for $(document).ready().
As for the latter, this is just an Immediately Invoked Function Expression.

(function ($) {
console.log('ready');
})(jQuery);

This function is simply an anonymous function which receives a parameter named $. The function is immediately invoked with some value (in this case jQuery) as the parameter.

IIFEs can also be used to isolate scopes and to avoid global variables in web applications which contain multiple JavaScript files. In this case a parameterless IIFE could be used:

(function () {
// x is only accessible within this IIFE
var x;
// do something...
})();

For more information regarding Immediately Invoked Function Expression, see this question: What is the purpose of a self executing function in javascript?

What jQuery(function($) { is for?

The code:

jQuery(function() {

is shorthand for

$( document ).ready(function() {

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.

https://learn.jquery.com/using-jquery-core/document-ready/

jQuery vs $ : "jQuery" = "$" - jQuery(function() is the same as $(function() - because other libraries use "$" you can explicitly use jQuery so you don't get the conflict.

by default, jQuery uses $ as a shortcut for jQuery. Thus, if you are using another JavaScript library that uses the $ variable, you can run into conflicts with jQuery.

https://learn.jquery.com/using-jquery-core/avoid-conflicts-other-libraries/

So you might use jQuery(function instead of $(function incase $ is defined elsewhere.


So to the code in the question, which is slightly different from other questions, the function call has a parameter that passes jQuery itself, so the code in the question:

jQuery(function($) {

ensures that all the code inside the function has access to $, while the code outside the function may or may not have $ defined to a different library.

This can be demonstrated by use of a different variable in place of the $ above:

jQuery(function(replacementJquery) {  replacementJquery("#id").text("updated")});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div id='id'>original</div>

What does (function () { })();mean?

It creates a closure, a private scope hiding the variables from the global object

// Somewhere...
var x = 2;

...
...
// Your code
var x = "foo" // you override the x defined before.

alert(x); // "foo"

But when you use a closure:

var x = 2;
// Doesn't change the global x
(function (){ var x = "foo";})();

alert(x); // 2

Regarding to the syntax, it's just a self executed function, you declare it and then execute it.

What does the $() function do in JavaScript?

That's not part of ECMAScript (JavaScript). It's just a function defined by some library of yours. Usually jQuery or PrototypeJS.

jQuery newbie: what does jQuery(function($) { ... }) means?

jQuery(function($) {

});

is the safest version of all three. It makes $ the local variable and thus gracefully avoids the conflicts with any other variables which possibly use $ symbol.

I think it was also added fairly recently, don't remember seeing it before.

These function all do the same things - execute some code when DOM is ready. $(document).ready(function(){}) is the original one, and it matches the underlying javascript API.

"$" and "jQuery" which accept function as an arguments were created as shortcuts to avoid repeating such a common construct. Accepting a function which accepts $ as its first argument is a further syntax sugar - now you get convenience of the closures without the need to do it yourself.



Related Topics



Leave a reply



Submit