why define function inside $()? - javascript

I came across a public JavaScript fragment that has the following lines of code:
$(function() {
var v1, v2;
v1 = new V1;
return v2 = new V2(v1);
});
The guts of the function are perfectly grokkable. But what is the significance of wrapping this in a $()?

$(fn) is a shortcut for $(document).ready(fn).

$(function() {...}); is a shorthand for $(document).ready(function(){...});
This means code inside will be executed as soon as DOM is ready. BTW its jquery syntax, there is no really pure javascript equivalent. It is not equivalent to window.onload = function(){...} which in jquery would be wrote: $(window).load(function(){...}); .
Don't be fooled by auto called anonymous function used in javascript:
(function(){...})()
or
(function(){...}())

$( fn ) is a shortcut for $(document).ready( fn ), which executes fn when the DOMContent is loaded.
In .ready docs you can see that these 3 are equivalent
$(document).ready(handler)
$().ready(handler) // this one is not recommended
$(handler)
With pure Javascript you could achieve the same behavior using
document.addEventListener("DOMContentLoaded", fn, false);
jQuery docs:
.ready
An example on jsFiddle

That notation is alias for $(document).ready(function() { ... });

Related

javascript autoexecuted function syntax

I've found this function and I'm not sure about what's doing
(function($) {
$(document).ready(function() {
/
$('.auto-scroll').off('click').on('click', function(event) {
event.preventDefault();
....
....
});
$("#btnBuscar").on("click", function() {
...
...
});
});
})(jQuery);
What is the meaning of pass JQuery as a parameter?
What is the meaning of pass JQuery as a parameter?
It's passing jQuery as an argument, and receiving it as the $ parameter. That way, within the anonymous function, it can use $ when using jQuery, rather than having to use jQuery. This is useful when you can't be sure that the global $ is already equal to jQuery (which it may not be, if a page has used noConflict to release it).

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...

Using $ instead of jQuery gives error

I'm using following jQuery code:
jQuery(document).ready(function() {
jQuery('#main').click(function(){
jQuery('#box').slideDown();
});
});
The above code works fine, however if I use $ instead of the jQuery, I get following error:
TypeError: $ is not a function
I understand that it is because of some conflict, but is there a way that I use $ in above code?
I have tried to use jQuery.noConflict(); also but it still gives same error.
Use this:-
jQuery(function($) {
$('#main').click(function(){
$('#box').slideDown();
});
});
Aliasing the jQuery Namespace
When using another JavaScript library, we may wish to call $.noConflict() to avoid namespace difficulties. When this function is called, the $ shortcut is no longer available, forcing us to write jQuery each time we would normally write $. However, the handler passed to the .ready() method can take an argument, which is passed the global jQuery object. This means we can rename the object within the context of our .ready() handler without affecting other code.
Reference
Try it like this,
$.noConflict();
jQuery(document).ready(function($) {
$('#main').click(function(){
$('#box').slideDown();
});
});
You could wrap it in a closure:
(function($){
// use $ as jQuery
})(jQuery);
You could use a closure:
(function ($) {
$(document).ready(function () {
$('#main').click(function () {
$('#box').slideDown();
});
});
})(jQuery)
First use noConflict.
var j = jQuery.noConflict();
then use
j(document).ready(function() {
j('#main').click(function(){
j('#box').slideDown();
});
});

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

Categories

Resources