1

What is the difference in $?

Question:

What does $ mean in the next example?

JS:

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

Can someone explain to me what is the difference between these 2 functions?

Thank you in advance

4
  • It is simply argument name. Commented Nov 7, 2013 at 13:39
  • this particular ( $ ) argument have some function/meaning in jQuery ? Or it is just argument named '$'. Commented Nov 7, 2013 at 13:42
  • Read the documentation. See the section: Aliasing the jQuery Namespace Commented Nov 7, 2013 at 13:42
  • It's the global jQuery Object. Commented Nov 7, 2013 at 13:42

2 Answers 2

3

$ is normally the name of the jQuery constructor. That is to say, it is the name of a function that you call every time you want to make a jQuery object. For instance:

$('div') 

It is normally a global variable, which means it is available throughout the page's Javascript. There is another variable jQuery, which normally points to exactly the same thing.

console.log($ === jQuery); // true 

However, it is possible to set $ to something else. Perhaps you want to use $ to mean something different in your code. Or perhaps you're using Prototype as well, which also uses the $ symbol to point to a function.

This is why the jQuery.noConflict() method exists: it stops $ referring to jQuery.

However, many authors prefer to use $ to refer to the jQuery constructor, because it's much more concise and readable. jQuery provides a helpful feature that allows them to do this easily.

When you do jQuery(document).ready(function(), you are assigning an event handler. The function will be run when the event is fired. What we can do is reassign $ to refer to jQuery solely in the scope of that callback function. This is aided by jQuery: every $(document).ready callback function is called with the jQuery constructor as the first argument, so you can use whatever name you choose within the function.

For instance:

var $ = 'apples'; jQuery(document).ready(function() { $('div'); // causes an error: "TypeError: string is not a function" }); jQuery(document).ready(function($) { $('div'); // works fine }); 

This functionality is documented in the jQuery API for the ready method, in the section entitled "Aliasing the jQuery Namespace".

Sign up to request clarification or add additional context in comments.

Comments

2

It's just the name of an argument.

See the documentation for ready:

the handler passed to the .ready() method can take an argument, which is passed the global jQuery object

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.