I'm pretty new to web programming.
Looking for a jQuery function I found something like:
jQuery(function($) {
$('#EleId1').click(function () {
//do stuff
}
$('#EleId2').click(function () {
//do other stuff
}
});
BUT if I remove "jQuery(function($) {" and the final "});" all is still working and I have no errors in the console.
So my question about "jQuery(function($) {" is:
Is it recommended (as best practice or for a more readable code) or is it needed for other reasons?
EDIT In the similar question "jQuery" is missing so it doesn't seems an identical question to the ones not knowing that "$" is equivalent of "jQuery" as explained in the below comment.
1 Answer 1
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
(jQuery)injection at the end. The parameter$is undefinedjQuery(document).ready(function($) { ... });$injQuery(function($)is, it's also jQuery. jQuery passes itself in the function.$is normally a global, but by passing it in, it becomes a local, which also allows you to ignore conflicts as, inside your function$becomes jQuery instead of the other library. As you don't have another library, you can use$outside the function as well (as it's global).