Passing a function to the jQuery selector - javascript

I already know about the advantages of wrapping your Javascript in a function like this:
(function () {
// code goes here
}())
But I've seen some scripts which accomplish this by passing the wrapper function to the jQuery object:
$(function () {
// blah blah blah blah blah
});
What's the advantage of doing it this way, or is it just a matter of personal taste? And does doing it the second way negate the need for $(document).ready()?

The first one
(function () {
// code goes here
}())
That is self executing function.
And the second function is jquery specific.
If you see the docs
The .ready() method can only be called on a jQuery object matching the current document, so the selector can be omitted.
The .ready() method is typically used with an anonymous function:
$(document).ready(function() {
// Handler for .ready() called.
});
Which is equivalent to calling:
$(function() {
// Handler for .ready() called.
});

Your first example is just standard JavaScript a self executing function, the second one is jQuery specific, and is a shortcut for $(document).ready(function () {});
see the jQuery documentation
and also this question for more info on self executing functions

(function(){}()) is an IIFE (Immediately-Invoked Function Expression) and is just an function executing Immediately
$(function(){}) is an jQuery callback fro when the browser is ready
i often have to add jQuery to sites that have mootools on them so to avoid $ conflicts i do somthing like this:
;(function($, app, undefined){
// code here
}(jQuery, myApp = window.myApp || {}))

Related

jQuery functions - re-invoking a self invoking function

I have a function that is I think is self invoked and I'm trying to figure out how to call it again.
This is how the function is declared:
jQuery(function setupFormInputHandlers(){
...
}
I try to put setupFormInputHandlers() in the developer tools console but I get an undefined error.
See jQuery document ready
// Passing a named function instead of an anonymous function.
function readyFn( jQuery ) {
// Code to run when the document is ready.
}
$( document ).ready( readyFn );
//invoke again
readyFn()
$ is just used as alias to jQuery so when you say $('x') you mean jQuery('x')..the main function is overloaded to make it familiar and to allow working with ease... also what you are asking about the function (may be you missed pasting other part)
$(function(){}); or
jQuery(function(){});
both are methods of calling anonymous function shorthand for
$(document).ready(function()
{
//your code
}
);`
in simple words it means "When the document loading complete register your an anonymous function"

different ways to execute javascript code?

I see
First
$(function() {
...
});
Second
(function() {
})();
Third
function() {
}
$(document).ready(function(){
});
Maybe there are more, what are the differences?
Your notation is mainly jQuery (atleast the ones with $)
This is shorthand for a DOM ready function, equivalent to the bottom one
This is a self executing function with the parameter specified in the trailing ()
This is a DOM ready function $(document).ready(function() {}); atleast, the function above it is simply a function.
so these indeed are a few different ways to execute javascript code, some of them are library dependent (using jQuery) others are done specifically because of differences in scope.
the first block:
$(function() {
...
});
is utilizing the js library jQuery that uses the namespace '$' what you are doing here is calling the jQuery '$' function passing in the first parameter of another anonymous function... this is a shorthand way to call $(document).ready(function(){});... both of those statements wait for the DOM to complete loading (via the onload event) before interpreting the javascript inside
the second block:
(function() {
})();
is a procedure called an (IIFE) Immediately-Invoked Function Expression... which in essense is defining an anonymous function and calling it immediately.
the third block:
function() {
}
$(document).ready(function(){
});
represents two things... the first function declared actually should have been named something like function myFunction(){...} and thus could be called later myFunction(parameters);
and finally $(document).ready(function(){}); is the javascript library jQuery's way of saying grab the 'document' element of the dom, and attach an event listen to it looking for the onload event, when that event is triggered execution the function passed as a parameter...

Is this a double document ready?

I'm working with a script and have found the following, which I really can't find any info of what it means
(function($) {
$(document).ready(function(e) {
... bla bla bla ...
});
}) (jQuery);
Is (function($){}) (jQuery); the same as $(function () {}); ? and if so, why would somebody define twice document.ready ?
No, it's not the same. It's an anonymous function which is being passed the jQuery object, to insure that it is available as the local variable $ within the scope of the function, even if the global variable $ is overwritten by another library. It is completely different than $(function () { }) and $(document).ready(function () { }).
This particular pattern is recommended in the jQuery plugin authoring documentation:
[When authoring a plugin] it's a best practice to pass jQuery to an IIFE (Immediately Invoked Function Expression) that maps it to the dollar sign so it can't be overwritten by another library in the scope of its execution.
(function( $ ) {
$.fn.myPlugin = function() {
// Do your awesome plugin stuff here
};
})( jQuery );
Is (function($){}) (jQuery); the same as $(function () {}); ?
No. The first is immediate invocation of an anonymous function, used primarily for preventing pollution of the global scope. In this case, it's also used to make sure that $ is a reference to jQuery, without worrying about overwriting $ elsewhere.
The second is the shorthand for binding a document ready handler with jQuery.
More reading:
What is the purpose of a self executing function in javascript?
What is the reason for this JavaScript immediate invocation pattern?
No it isn't, (function($){}) (jQuery); is an IIFE(Immediately invoked function expression) passing jQuery as a parameter and using $ to represent it in the function scope so that no conflicts will occur if another library that uses $ is loaded without using jQuery.noConflict.
Nope
(function(){})();
is executed as soon as the browser encounters that script.
.ready() is an event that is triggered after the entire document is parsed
No it's not. It is a closure with a document ready handler inside it. It is used to ensure that the $ within the enclosure is reserved for jQuery and does not interfere with any other library.
A nice clear explanation here;
http://jquery-howto.blogspot.com/2008/12/what-heck-is-function-jquery.html

Do self executing functions run at dom ready?

Before I heard about self executing functions I always used to do this:
$(document).ready(function() {
doSomething();
});
function doSomething()
{
// blah
}
Would a self executing function have the same effect? will it run on dom ready?
(function doSomething($) {
// blah
})(jQuery);
Nope. A self executing function runs when the Javascript engine finds it.
However, if you put all of you code at the end of your document before the closing </body> tag (which is highly recommended), then you don't have to wait for DOM ready, as you're past that automatically.
If all you want is to scope your $ variable, and you don't want to move your code to the bottom of the page, you can use this:
jQuery(function($){
// The "$" variable is now scoped in here
// and will not be affected by any code
// overriding it outside of this function
});
It won't, it will be ran as soon as the JavaScript file is executed.
No, self-executing javascript functions run right there.
If you want to create a DOM ready function, write the following:
$(function() {
// this will run on DOM ready
});
Which is a shorthand of:
$(document).ready(function() {
});
No, the self-executing function run immediatly after you "declare" it on your code. Even if it's located on an external .js file.
In your example, there is a possibility that your function will execute and the value of jQuery is undefined. If you want your code to be executed on DOMReady, continue using
$(document).ready(function(){
doSomething();
});
or
$(function(){
doSomething();
});
or even
window.onload = function(){
doSomething();
}
$(document).ready(function() { ... }); simply binds that function to the ready event of the document, so, as you said, when the document loads, the event triggers.
(function($) { ... })(jQuery);
is actually a construct of Javascript, and all that piece of code does is pass the jQuery object into function($) as a parameter and runs the function, so inside that function, $ always refers to the jQuery object. This can help resolve namespacing conflicts, etc.
So #1 is executed when the document is loaded, while #2 is run immediately, with the jQuery object named $ as shorthand
$(document).ready(function(){ ... }); or short $(function(){...});
This Function is called when the DOM is ready which means, you can start to query elements for instance. .ready() will use different ways on different browsers to make sure that the DOM really IS ready.
(function(){ ... })();
That is nothing else than a function that invokes itself as soon as possible when the browser is interpreting your ecma-/javascript. Therefor, its very unlikely that you can successfully act on DOM elements here.
jQuery document.ready vs self calling anonymous function

why the $(function () executed always

I am wondering why the $(function () {} is getting executed all the time. function test(0 is not. what's the difference between those two?
jQuery's extreme shorthand tends to trick the eye sometimes.
Look closely at the construct: A function named $ gets called, with the function as an argument. This is not equal to defining a function for later use like function test() { .... }
$ is jQuery's "document ready" shortcut. The function passed to it will get executed once the document is loaded.
this is a short form for document ready.
$("document").ready(function(){});
so it will execute every time document loads

Categories

Resources