2

I've never seen anyone do this before. Could anyone enlighten me on this? This was taken from here.

jQuery(function ($) { //What's with the $ as an argument? $('#flux').bind('scroll', function () { if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) { alert('end reached'); } }) }); 

It appears he can declare a function and run it at the same time.

4
  • Is this question about the "$" argument only, or is this the first time you encounter jQuery code? Commented Apr 7, 2014 at 9:23
  • learn.jquery.com/using-jquery-core/document-ready Commented Apr 7, 2014 at 9:27
  • @ArlaudPierre No sir, I wasn't aware that this was another way to do $(document).ready();. On another note, I just tested the function without the $ argument and it works regardless. Does it serve any purpose? Commented Apr 7, 2014 at 9:35
  • @Geoyws check out the discussion I had with Misiur on his answer, it's here "to avoid conflicts with some other global $ variable". Commented Apr 7, 2014 at 9:36

2 Answers 2

2

It's shorthand for http://api.jquery.com/ready/

The argument $ is in fact jQuery - it's often used to avoid conflicts with some other global $ variable

See: http://api.jquery.com/jQuery/#jQuery3

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

4 Comments

No example of the page uses "$" as the function argument.
I'm not sure if I understand you correctly, but in the second link the last example uses $ as an argument. It's kinda like closures, where you pass global variables, but aliased: (function($, hello, undefined) { /* ... */ })(jQuery, 'something');
Oh okay, I only check it on the ready page, my bad. Do we know of any other plugin that conflicts with jQuery?
learn.jquery.com/using-jquery-core/… - prototype used to be a big problem, also better safe than sorry!
0

It appears he can declare a function and run it at the same time.

The function is not run here, it is just passed to jQuery (which will run it when the document is ready).

function ($) { //What's with the $ as an argument?

This is the Javascript concept of a module:

Instead of having the function refer to a global $ (which may end up being something unexpected), you pass in the $ as a parameter (jQuery will do that for you here). Then within the function body $ refers to that local object.

I just tested the function without the $ argument and it works regardless.

Yes, but that is because you also have a global object $. The idea of passing it in explicitly is to avoid having the function access the global scope.

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.