On document ready with an argument? [duplicate] - javascript

This question already has answers here:
explain this javascript function declaration "jQuery(function($){}"
(3 answers)
Closed 4 months ago.
can anyone help me understand what the following code does?
$(function($) {
$.supermodal();
});
I see it's very similar to "wait for document to finish loading before running supermodal". But I don't understand the 2nd and 3rd dollar signs (I realize they could be any arbitrary variable names).
FWIW, this is from here, where author has an additional usage for changing default values.
Sorry, seems like it should be simple, but it's one of those things that's hard to search for when you don't know what it's doing (e.g., this isn't right).
Thanks!

The first $ is the global variable to which jQuery is assigned.
The second $ is a function argument. It defines a variable called $. When you pass a function to jQuery it will be called when the DOM is ready or immediately (whichever is later) and jQuery (specifically the instance of jQuery which was passed the callback function) will be passed to the first argument. This is useful when you are dealing with multiple things which might be assigned to the global $ variable (including multiple versions of jQuery with different plugins … which does happen occasionally).
The third $ is making use of that argument.

It seems that jquery executes the function it receives as argument. Calling it with first argument as the reference to jquery itself.
Now the only question is why. From the docs it is to have a failsafe $ alias
jQuery(function( $ ) {
// Your code using failsafe $ alias here...
});

From the documentation:
Use both the shortcut for $(document).ready() and the argument to write failsafe jQuery code using the $ alias, without relying on the global alias.
jQuery(function( $ ) {
// Your code using failsafe $ alias here...
});

Related

Need code explanation in JavaScript [duplicate]

This question already has answers here:
jQuery document ready function
(7 answers)
Closed 7 years ago.
I'm new to javascript. In my current project I'm using very often this code:
$(function() {
// init fields and constants...
file_input_1 = document.getElementById("input-1");
file_input_2 = document.getElementById("input-2");
[...]
});
I know what it does (executes on page load, some kind of file constructor?), but I don't know why it happen.
What is $ and why my browser executes this code?
$ is just a name, you can name a variable/function/object like that. $ is set by jQuery and is an alias to the identifier jQuery, which is a function.
jQuery is just coded in a way that if you pass a function as parameter to $, it acts the same way as $(document).ready
Picture it kind of like this (of course, jQuery is much more complex):
function $(yourFn) {
yourFn();
}
// Alerts "Executed"
$(function () {
alert("Executed");
});
$() is a reference to jQuery. It is convention to import jQuery as $ for easier calling of jQuery functions.
So that function calls jQuery, and when jQuery finishes loading, it runs the callback (your function).
Here is the documentation for this functionality: jQuery()
$ is an identifier which, in that context, is a variable.
It will be defined by some other piece of code (or throw a reference error when you try to call its value as a function).
It often has the jQuery function from the jQuery library assigned to it.

Self-invoking function jQuery [duplicate]

This question already has answers here:
What is the purpose of this? (function ($) { //function code here })(jQuery);
(4 answers)
Closed 9 years ago.
I noticed that in some places, jQuery code is wrapped in a self-invoking function like below. Why is this done, in what cases is this useful and in what cases is an unnecessary boilerplate?
function( $ ) {
...
}( jQuery );
The short answer: To prevent variable name conflicts. It is not always needed, but good practice in order to create conflict free reusable code.
The long answer: In javascript the $ symbol is just another variable. jQuery uses it because it is a nice shorthand instead of having to type out jQuery each time, but so can any other code (including other libraries).
To prevent conflict with other uses of a variable at the same scope (in this case $ at the "global" scope) it is common for code to be wrapped in a self-invoking function with the "conflict-free" variables passed as the function parameters. This then creates a new scope where your variable won't interfere with other uses of that variable. That way you can pass the full named variable & uses it with whatever name you want within the anonymous function.
So, when creating conflict free reusable code it is good practice to use this methodology:
(function( $ ) {
...
})( jQuery );
Along these lines you will also see the following format:
(function( $, window, undefined ) {
...
})( jQuery, window );
In this instance undefined is simply used for readability to indicating that no more arguments are passed to the function.
In case you want to avoid conflict regarding use of $
function( $ ) {
...
}( jQuery );
Inside this function you can use $ without having to worry about it's use outside of it as inside that function, $ always refers to the jQuery object.
This is helpful while creating jQuery plugins,You will see jQuery plugin's use this kind of function to avoid conflicts with other plugins.
Reference : http://learn.jquery.com/plugins/basic-plugin-creation/
In function scope $ is local variable that not conflict with any other global $.

explain this javascript function declaration "jQuery(function($){}"

i came across this piece of script in the source code of a chrome extension. it declares a function:
jQuery(function($){
$('#actionCopy').click(function(e){
Action.copy();
});
});
what is that jQuery word used at the beginning of the function? and what does the dollar sign that is used as the function argument do? ( function($) )
Passing in a function as first argument into the jQuery constructor function is just a shortcut for .ready().
jQuery(document).ready(function() {
});
jQuery will be kind enough to pass in the jQuery object reference into the callback which you pass in for the .ready handler. That means, you can just savely access the jQuery object using the dollar sign $ within.
what is that jQuery word used at the beginning of the function?
It refers to a function called jQuery (defined by the library available from http://jquery.com).
That particular function is horribly overloaded, but in this case (when it receives one argument that is a function) it means "Bind this function to the document ready event" (with some pollyfill for the benefit of browsers that don't support that event natively).
and what does the dollar sign that is used as the function argument do?
The same as a letter a or the word foo or anything else. It defines the variable name that the argument will be passed to. There is nothing special about the $ character in JavaScript variable names.
jQuery is popular javascript library. $ is the shorthand for accessing jQuery object. Passing $ in function 'function($)' will make sure that $ will not be conflicted with any other javascript library used.

I'd like to understand the jQuery plugin syntax

The jQuery site lists the basic plugin syntax for jQuery as this:
(function( $ ){
$.fn.myPlugin = function() {
// there's no need to do $(this) because
// "this" is already a jquery object
// $(this) would be the same as $($('#element'));
this.fadeIn('normal', function(){
// the this keyword is a DOM element
});
};
})( jQuery );
I'd just like to understand what is going on there from Javascript's point of view, because it doesn't look like it follows any syntax I've seen JS do before. So here's my list of questions:
If you replace function($)... with a variable, say "the_function", the syntax looks like this:
(the_function)( jQuery );
What is "( jQuery );" doing? Are the parenthesis around the_function really necessary? Why are they there? Is there another piece of code you can give that is similar?
It begins with function( $ ). So it's creating a function, that as far as I can tell will never be run, with the parameter of $, which is already defined? What is going on there?
Thanks for the help!
function(x){
x...
}
is just a function without a name, that takes one argument, "x", and does things with x.
Instead of 'x', which is a common variable name, you can use $, which is a less common variable name, but still legal.
function($){
$...
}
I'll put it in parentheses to make sure it parses as an expression:
(function($){
$....
})
To call a function, you put () after it with a list of arguments. For example, if we wanted to call this function passing in 3 for the value of $ we would do this:
(function($){
$...
})(3);
Just for kicks, let's call this function and pass in jQuery as a variable:
(function($){
$....
})(jQuery);
This creates a new function that takes one argument and then calls that function, passing in jQuery as the value.
WHY?
Because writing jQuery every time you want to do something with jQuery is tedious.
WHY NOT JUST WRITE $ = jQuery?
Because someone else might have defined $ to mean something else. This guarantees that any other meanings of $ are shadowed by this one.
(function( $ ){
})( jQuery );
That is self-executing anonymous function that uses $ in argument so that you can use it ($) instead of jQuery inside that function and without the fear of conflicting with other libraries because in other libraries too $ has special meaning. That pattern is especially useful when writing jQuery plugins.
You can write any character there instead of $ too:
(function(j){
// can do something like
j.fn.function_name = function(x){};
})(jQuery);
Here j will automatically catch up jQuery specified at the end (jQuery). Or you can leave out the argument completely but then you will have to use jQuery keyword all around instead of $ with no fear of collision still. So $ is wrapped in the argument for short-hand so that you can write $ instead of jQuery all around inside that function.
If you even look at the source code of jQuery, you will see that everything is wrapped in between:
(function( window, undefined ) {
// jQuery code
})(window);
That is as can be seen also a self-executing anonymous function with arguments. A window (and undefined) argument is created and is mapped with global window object at the bottom (window). This is popular pattern these days and has little speed gain because here window is will be looked into from the argument rather than global window object which is mapped below.
The $.fn is jQuery's object where you create your new function (which is also an object) or the plugin itself so that jQuery wraps your plugin in its $.fn object and make it available.
Interestingly, I had answered similar question here:
JavaScript / jQuery closure function syntax
You can also check out this article to know more about self-executing functions that I had written:
Javascript Self-executing Functions
The basic plugin syntax allows you to use $ to refer to jQuery in the body of your plugin, regardless of the identify of $ at the time the plugin is loaded. This prevents naming conflicts with other libraries, most notably Prototype.
The syntax defines a function that accepts a parameter known as $ so you can refer to it as $ in the function body, and then immediately invokes that function, putting jQuery in as the argument.
This also helps not pollute the global namespace (so declaring var myvar = 123; in your plugin body won't suddenly define window.myvar), but the main ostensible purpose is to allow you to use $ where $ may have since been redefined.
You're dealing with a self-invoking anonymous function there. It's like "best practice" to wrap a jQuery plugin within such a function to make sure, that the $ sign is bound to the jQuery object.
Example:
(function(foo) {
alert(foo);
}('BAR'));
This would alert BAR when put into a <script> block. The parameter BAR is passed to the function which calls itself.
The same principle is happening in your code, the jQuery object is passed to the function, so $ will refer to the jQuery object for sure.
The jQuery at the end passes itself (jQuery) over to the function, so that you can use the $ symbol within your plugin. You ccould also do
(function(foo){
foo.fn.myPlugin = function() {
this.fadeIn('normal', function(){
});
};
})( jQuery );
To find a clear explanation of this and other modern javascript tricks and common practices, I recommend reading Javascript Garden.
http://bonsaiden.github.com/JavaScript-Garden/
It's especially useful, because many of these patterns are widely used in many libraries but not really explained.
The other answers here are great, but there is one important point that hasn't been addressed. You say:
So it's creating a function, that as far as I can tell will never be run, with the parameter of $, which is already defined?
There is no guarantee that the global variable $ is available. By default, jQuery creates two variables in the global scope: $ and jQuery (where the two are aliases for the same object). However, jQuery can also be run in noConflict mode:
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
jQuery.noConflict();
</script>
When you call jQuery.noConflict(), the global variable $ is set back to whatever it was before the jQuery library was included. This allows jQuery to be used with other Javascript libraries that also use $ as a global variable.
If you wrote a plugin that relied on $ being an alias for jQuery, then your plugin would not work for users running in noConflict mode.
As others have already explained, the code you posted creates an anonymous function that is called immediately. The global variable jQuery is then passed in to this anonymous function, which is safely aliased as the local variable $ within the function.

How do jQuery's namespaces work? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
What does this JavaScript/jQuery syntax mean?
I specifically mean when you do this:
(function ($) {
...
})(jQuery);
I've never seen that kind of syntax before. How does the function get called? I understand when you do it like this:
jQuery(function ($) {
...
});
because the function is being passed to jQuery, and jQuery can just run any function passed as a parameter when the DOM's ready, but the first one's different.
Duplicate of What does this JavaScript/jQuery syntax mean?
I'll post my answer here, though seeing as Jeff Attwood seems to want us to embrace duplication: (https://blog.stackoverflow.com/2010/11/dr-strangedupe-or-how-i-learned-to-stop-worrying-and-love-duplication/)
This convention is used when writing plugins to ensure there is no confilict with other Javascript libraries using the $ notation, whilst ensuring the plugin author can still use this notataion:
(function($){
...
})(jQuery);
The author is declaring an anonymous function with a single parameter ($), then immediately calling it and passing the jQuery object to it. This ensures the function is called and that everything in it is defined.
A longer notation might be:
function MyDefs($){
...
}
MyDefs(jQuery);
Although that would create a variable MyDefs in the global namespace. The anonymous function pattern leaves the global namespace empty, avoiding conflicts.
It's an anonymous function. When you write:
(function ($){
..
})(jQuery);
It is mostly equivalent to:
function the_function($) {
..
}
the_function(jQuery);
The only difference being that the first does not create a function called the_function and therefore created no risk of accidentally overwriting an existing function or variable with that name. And of course, all of it is equivalent to:
function the_function() {
var $ = jQuery;
..
}
the_function();
The point of this construct is that any variables defined inside the_function are local and therefore cannot accidentally overwrite any variables or functions in the global scope. For instance, the code inside the function uses $ to represent the jQuery object, but this would conflict with other libraries that use $ as well (such as Prototype). By wrapping the usage of $ inside a function, the Prototype code outside the function remains unaffected.

Categories

Resources