The code:
jQuery(function() {
is shorthand for
$( document ).ready(function() {
A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.
https://learn.jquery.com/using-jquery-core/document-ready/
jQuery
vs $
: "jQuery" = "$" - jQuery(function()
is the same as $(function()
- because other libraries use "$" you can explicitly use jQuery so you don't get the conflict.
by default, jQuery uses $ as a shortcut for jQuery. Thus, if you are using another JavaScript library that uses the $ variable, you can run into conflicts with jQuery.
https://learn.jquery.com/using-jquery-core/avoid-conflicts-other-libraries/
So you might use jQuery(function
instead of $(function
incase $ is defined elsewhere.
So to the code in the question, which is slightly different from other questions, the function call has a parameter that passes jQuery itself, so the code in the question:
jQuery(function($) {
ensures that all the code inside the function has access to $
, while the code outside the function may or may not have $
defined to a different library.
This can be demonstrated by use of a different variable in place of the $
above:
jQuery(function(replacementJquery) {
replacementJquery("#id").text("updated")
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='id'>original</div>
If you aren't use another library that uses $
then you can safely use:
$(function() {
if you are writing a library that may be used with other libraries in addition to jQuery, then use:
jQuery(function($) {
and safely use $
inside the function