I'd like to know exactly what's going on here. I know what $(document).ready(function() {...}); does and when it comes into effect. Same goes for jQuery(function($) {...}.
But what does this do?
!function ($) {
$(function(){
var $window = $(window)
//normal jquery stuff
})
}(window.jQuery)
Is it loaded when jQuery is loaded instead of when the document is 'ready'?
It creates a closure in which the variable $ is assigned the value of window.jQuery.
The intention is to allow the uninformatively named variable $ to be used as a shortcut for jQuery without conflicting with the large number of other libraries and custom functions that also use $ as a variable name.
Using the ! operator before the function causes it to be treated as an expression
!function () {}()
The syntax you're looking at is used for setting up a jQuery closure. This is used to ensure that the jQuery $ variable is garuanteed to be available and correct within the code; ie it can't be overwritten in the global scope by anything else (which is possible if you're using multiple libraries, etc).
This technique is often used by jQuery plugin authors -- if you're interested in finding out more, the docs are here, and explain in more detail why you'd want to wrap your jQuery code in a function like this.
The only point of interest that's different in your example is that in the docs, the function is wrapped in brackets, whereas in the example you've given it's preceded by a !
The ! is a not operator, but doesn't actually get used for anything; I think it's just there instead of the brackets to save a single character of code. Probably helpful if you're into minifying javascript.
Not quite sure but I guess this is somewhat equivalent to (function(){})() approach and it's about js closures. And it ensures $ and jQuery are the same thing
The '!' is a 'not' operator. It doesn't do anything in the code. The only reason it is there is to signify that the function will execute immediately.
You may also see functions wrapped in parenthesis instead.
(function() {}());
Whatever is used is personal preference.
Related
(function ($, undefined) {
. . .
})(jQuery);
I see this everywhere, but I don't understand why we're sending jQuery as a parameter in a self contained function. jQuery is already being referenced. Also, why are we defining undefined as a parameter?
Passing $ to the anonymous function ensures that the namespace is protected (i.e. does not conflict with other libraries that also use the $ shortcut).
Oftentimes, undefined is passed to a function to ensure that the variable is truly undefined. For example, consider the following code exerpt:
undefined = '123';
if(myVar == undefined)
{
// Will only ever execute if myVar == '123'
}
As noted in the comments though, unless you're writing a plugin or some such, using jQuery(function($) { }) is probably a better approach, since it protects the $ shortcut and also provides a DOMReady event, meaning less code is required to achieve the same result.
If you need to check against undefined, you might also want to consider using $.noop().
It's possible that $ or undefined might have their values changed by subsequent code, eg. if you're mixing multiple JS libraries, or using multiple versions of a library. By capturing your own copy of $ and undefined, you guard against that.
(function ($, undefined) {
. . .
})(jQuery);
with that you'll be sure that $ is jQuery inside the function(whatever jQuery is in your script).
It doesnt prevent you from overwriting jQuery variable though,so use it only if you really need it( or you are creating a plugin and distributing a jquery plugin).
As for undefined,it will force undefined to actually be undefined,as undefined can be overwritten in some js engines.
I don't grok the idea/purpose/use of Javascript $, as in
function $(id) {
return document.getElementById(id);
}
Could someone please explain or point me at an explanation?
Thanks!
-- Pete
When you see JavaScript code that involves lots of $(foo) function calls, it's probably using either the jQuery or the Prototype web development frameworks. It's just an identifier; unlike a lot of other languages, identifiers (function and variable names) can include and start with "$".
In your code it is the name of a function.
function $(id) { return document.getElementById(id); }
$("my_id")
function myfunc(id) { return document.getElementById(id); }
myfunc("my_id")
Two functions, two different identifiers.
Most commonly this is used by JQuery - specifically, JQuery creates an object with a reference of $ which has various methods to simplify page manipulation.
It's technically possible for anything to attach a class to $
It's just the name of a function called $(). The dollar sign ($) is a valid character for identifiers in JavaScript. jQuery, for example, uses it as a shorthand alias for the jQuery() function.
There are two main reasons to use $ as a function name, especially in frameworks like jQuery:
It's short but distinctive - you're going to use it all over the place, so you don't want it to take up too much space.
When used as a DOM element selector, the function and its parameters together kind of look like a Perl/PHP/Java properties variable - and it kind of works like that as well, since the main purpose is to do something with the selected DOM elements.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
what is difference of $(function(){ }); and $(document).ready(function() { }) ;?
What are the differences between $(document).ready(function(){}) vs $(function(){})
and should I write it in the $ form or the new jQuery(document).ready(function(){ }) way?
If I have google api loaded is google.setOnLoadCallback(function() { a better way? or is it the same thing?
I've also seen people use $(function($){})
Can somebody help me, I'm lost. I bugs me when I don't know the code I write. I guess I should read through the library. Are the all being defined as the same thing?
The two ways are equivalent, I personally prefer the second, $(function() {}); it's just a shortcut for document ready.
About the new jQuery(document)... construct, you don't really need to use the new operator, jQuery will use it internally if you don't.
The argument that the ready handler function receives, is the jQuery object itself.
That's quite useful where you have to run jQuery in compatibility mode with other libraries, for example:
jQuery(function ($) {
// use $ here
});
The $ argument inside the callback will refer to the jQuery object, outside that function it might refer to another library like PrototypeJS.
$(document).ready(function() {});
$(function() {});
The two statements are actually the exact same. So the second call is just a shortcut for the first.
The $ notation is again only a shortcut for jQuery. If you have loaded jQuery into your website you can use both. Especially if you don't load other JS librarys, which maybe also use the $ sign. That brings us to your mentioned
(function($){
}(jQuery));
call. What is done here is to make sure, that within your created function expression the $ sign references to the jQuery object. You're calling that anonymous function (which has $ as parameter) and pass the jQuery object in.
I encourage to read some articles that are very useful to understand somethings in jQuery ( and of course in javascript ), this articles explain how to create a jQuery plugin, but reading it you will understand some basic and important things, like closures witch is the meaning in this (function($){}(jQuery)); statement.
http://www.authenticsociety.com/blog/jQueryPluginTutorial_Beginner
In the following JavaScript code there is a dollar ($) sign. What does it mean?
$(window).bind('load', function() {
$('img.protect').protectImage();
});
Your snippet of code looks like it's referencing methods from one of the popular JavaScript libraries (jQuery, ProtoType, mooTools, and so on).
There's nothing mysterious about the use of $ in JavaScript. $ is simply a valid JavaScript identifier. JavaScript allows upper- and lower-case letters (in a wide variety of scripts, not just English), numbers (but not at the first character), $, _, and others.¹
Prototype, jQuery, and most javascript libraries use the $ as the primary base object (or function). Most of them also have a way to relinquish the $ so that it can be used with another library that uses it. In that case you use jQuery instead of $. In fact, $ is just a shortcut for jQuery.
¹ For the first character of an identifier, JavaScript allows "...any Unicode code point with the Unicode property “ID_Start”..." plus $ and _; details in the specification. For subsequent characters in an identifier, it allows anything with ID_Continue (which includes _) and $ (and a couple of control characters for historical compatibility).
From another answer:
A little history
Remember, there is nothing inherently special about $. It is a variable name just like any other. In earlier days, people used to write code using document.getElementById. Because JavaScript is case-sensitive, it was normal to make a mistake while writing document.getElementById. Should I capital 'b' of 'by'? Should I capital 'i' of Id? You get the drift. Because functions are first-class citizens in JavaScript, you can always do this:
var $ = document.getElementById; //freedom from document.getElementById!
When Prototype library arrived, they named their function, which gets the DOM elements, as '$'. Almost all the JavaScript libraries copied this idea. Prototype also introduced a $$ function to select elements using CSS selector.
jQuery also adapted $ function but expanded to make it accept all kinds of 'selectors' to get the elements you want. Now, if you are already using Prototype in your project and wanted to include jQuery, you will be in problem as '$' could either refer to Prototype's implementation OR jQuery's implementation. That's why jQuery has the option of noConflict so that you can include jQuery in your project which uses Prototype and slowly migrate your code. I think this was a brilliant move on John's part! :)
That is most likely jQuery code (more precisely, JavaScript using the jQuery library).
The $ represents the jQuery Function, and is actually a shorthand alias for jQuery. (Unlike in most languages, the $ symbol is not reserved, and may be used as a variable name.) It is typically used as a selector (i.e. a function that returns a set of elements found in the DOM).
As all the other answers say; it can be almost anything but is usually "JQuery".
However, in ES6 it is a string interpolation operator in a template "literal" eg.
var s = "new" ; // you can put whatever you think appropriate here.
var s2 = `There are so many ${s} ideas these days !!` ; //back-ticks not quotes
console.log(s2) ;
result:
There are so many new ideas these days !!
The $() is the shorthand version of jQuery() used in the jQuery Library.
In addition to the above answers, $ has no special meaning in javascript,it is free to be used in object naming. In jQuery, it is simply used as an alias for the jQuery object and jQuery() function.
However, you may encounter situations where you want to use it in conjunction with another JS library that also uses $, which would result a naming conflict. There is a method in JQuery just for this reason, jQuery.noConflict().
Here is a sample from jQuery doc's:
<script src="other_lib.js"></script>
<script src="jquery.js"></script>
<script>
$.noConflict();
// Code that uses other library's $ can follow here.
</script>
Alternatively, you can also use a like this
(function ($) {
// Code in which we know exactly what the meaning of $ is
} (jQuery));
Ref:https://api.jquery.com/jquery.noconflict/
From the jQuery documentation describing the jQuery Core Object:
Many developers prefix a $ to the name of variables that contain jQuery
objects in order to help differentiate. There is nothing magic about
this practice – it just helps some people keep track of what different
variables contain.
Basic syntax is: $(selector).action()
A dollar sign to define jQuery A (selector) to "query (or find)" HTML elements A jQuery action() to be performed on the element(s)
I know a bit of JavaScript, and can work fine with jQuery. I just don't get why everything is referenced from $(). My understanding is that $ is never needed in JavaScript (unlike for example PHP, where every variable is prefixed with $).
I've looked through the source code, and it doesn't really make sense. Is it just that $ is the function name (for example, it could have easily have been jQuery(), but they selected $?) I assume not, though, as I don't think $ is valid in function names in JavaScript?
$ is just a global variable that's also a reference to the jQuery function, it's $ on purpose so it's less to type. $ is perfectly valid for a function name in ECMAScript:
function $(){}; alert(typeof $);
Note that if you're using multiple libraries you can use function scope to avoid clashing dollar sign variables, eg:
jQuery.noConflict();
(function($){
$('body').hide();
})(jQuery);
$() is the same as jQuery(). Also, $ is a valid function name.