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.

Community
  • 1
  • 1
geoyws
  • 3,326
  • 3
  • 35
  • 47
  • Is this question about the "$" argument only, or is this the first time you encounter jQuery code? – Pierre Arlaud Apr 07 '14 at 09:23
  • http://learn.jquery.com/using-jquery-core/document-ready/ – Arun P Johny Apr 07 '14 at 09: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? – geoyws Apr 07 '14 at 09:35
  • @Geoyws check out the discussion I had with Misiur on his answer, it's here "to avoid conflicts with some other global $ variable". – Pierre Arlaud Apr 07 '14 at 09:36

2 Answers2

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

Misiur
  • 5,019
  • 8
  • 38
  • 54
  • No example of the page uses "$" as the function argument. – Pierre Arlaud Apr 07 '14 at 09:23
  • 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');``` – Misiur Apr 07 '14 at 09:25
  • Oh okay, I only check it on the ready page, my bad. Do we know of any other plugin that conflicts with jQuery? – Pierre Arlaud Apr 07 '14 at 09:28
  • 2
    http://learn.jquery.com/using-jquery-core/avoid-conflicts-other-libraries/ - prototype used to be a big problem, also better safe than sorry! – Misiur Apr 07 '14 at 09:30
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.

Thilo
  • 257,207
  • 101
  • 511
  • 656