Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does it do to invoke jQuery with a function expression argument, like `jQuery(function() { … })`?

jQuery(function ($) { /* … */ });

I am trying to learn jQuery and came across some code that started like the above statement. What does that mean?

like image 251
Sheehan Alam Avatar asked Jan 17 '26 20:01

Sheehan Alam


2 Answers

That is a shortcut for:

jQuery(document).ready(function($) {
    // ...
});

It sets up an event handler for when the document is ready to have its DOM manipulated. It's good practice to initiate your jQuery code after the document is ready. The first parameter $ references the jQuery object so you can use $ in place of jQuery in your code.

like image 70
Jacob Avatar answered Jan 20 '26 10:01

Jacob


I believe this allows you to abstract $ into an anonymous function. As a few different javascript libraries use the $ syntax you don't want to create conflicts. So instead you call jQuery using its explicit identifier jQuery and pass in $. Now you can use $ all you want inside the anonymous function and not need to worry about conflicting with other libraries.

like image 29
mrtsherman Avatar answered Jan 20 '26 11:01

mrtsherman