Javascript vs jQuery Function Difference? - javascript

I've been making a program and I want to know the difference between starting two functions like so:
$(function () {
//content
});
and
function Name () {
//content
}
Also, why can't I name the first example? I tried changing the first example to the second type, and the function stopped working fully. I've used jQuery with the first example and everything was fine, but with a different example, the function stopped working.
So what's the difference?

$(function () {}); this is shortcut for $(document).ready(function(){});
while this:
function Name () {
//content
}
is standard javascript function.
http://api.jquery.com/ready/
http://www.w3.org/wiki/JavaScript_functions

The first is a function expression that is used for the jQuery ready event, while the second is a function.
Using $(function(){...}); is shorthand for $(document).ready(function(){...});.
The ready event happens when the document has completed loading, so the event handler will run automatically. A regular function doesn't run at all unless you call it.
You can naturally use a regular function instead of the function expression for the event handler:
function readyHandler() {
...
}
$(readyHandler); // or $(document).ready(readyHandler);
A function expression can be named, for example:
var x = function y() { ... };
However, the name of the function expression (y in the example) is not global, it's only usable inside the function itself. Also, the exact implementation of this differs between browsers, so you should avoid using it.

The first one is a so-called anonymous function. It gets executed on the document ready event
$(document).ready(...);
and is jQuery convention. Since you cannot call it directly, it has no / needs no name.
The second version is a standard function that you can call by name at any time.
If you change the first one to the second notation, it will no longer run at document ready automaticly. Safe way is to move the "worklaod" into a function with the second notation, and create a line with the first notation that calls the funciton. That way you have the best of both worlds: a separately callable function, and simple auto-execution.

The first one:
$(function () {
//content
});
is passing an anonymous function to the jQuery object $, equivalent to $(document).ready(function(){});
the second is just a JavaScript function named Name.

Related

Running jQuery declared function with .on function

Currently this function works:
$("#email_address_input").on('focusout', function(){
emailValidationCheck($(this));
});
function emailValidationCheck(e){
...
}
So basically, if the email address input element is focused out, then an anonymous function runs, which calls the declared function emailValidationCheck (and of course, that declared function takes as an argument the email address input element).
That anonymous function feels redundant. All it does is call the declared function, so it seems to me like it should be taken out.
So, what I tried to do was call the declared function directly upon the event firing, as opposed to calling the anonymous function, which in turn calls that declared function. Like this (warning, it doesn't work as expected):
$("#email_address_input").on('focusout', emailValidationCheck($(this)));
Question: How can I get this to work? Or is the original answer best practice? Basically what I am trying to do is: when the focusout event fires off on the specified element, I want to execute the emailValidationCheck function, where the passed in argument is the element where this all this stuff is happening on.
Thanks!
You don't need to use anonymous functions as callbacks for events. You can easily call a defined function without using the () precursor (because including that will essentiall pass the return value of emailValidationCheck to the callback, rather than the function reference itself). For example:
$("#email_address_input").on('focusout', emailValidationCheck);
Now, your emailValidationCheck function will receive the event in the e variable that you define in the function constructor.
Because the function has been bound as a callback, $(this) is also available within it. For example:
function emailValidationCheck(e)
{
console.log( e ); // logs the event
console.log( $(this) ); // logs the jQuery object that lost focus
}
jsFiddle Demo
That's not how javascript works. The .on() function wants a function as a parameter. You can either pass an anonymous function or the name of a function. As soon as you put () at the end, it executes the function inline and passes the result to the .on() function.

Meaning of statement in JS

Trying to figure out what this means in javascript.
(function(document) { ... } )(document);
It is isn't using jQuery, so is this just a javascript way of making this wait till document is ready to execute?
Thanks.
This won't wait for the document to be ready, this will execute the content of the function immediately. Putting the function definition in parenthesis makes it an expression, which returns a value being the function, making it directly executable. This pattern is called an Immediately-Invoked Function Expression (IIFE).
This is probably used in conjunction with a minifier like the Closure Compiler.
Inside the function, document is a local variable. This makes it possible for the minifier to reduce its name to a one or two character name.
Note also that all variables defined inside the function will be local : they won't leak in the global scope, which may be interesting if this is only part of the script.
This creates an anonymous function that takes a single argument, and immediately calls it passing document as the argument.
This:
function(document) { ... }
creates a function taking one paremeter.
This:
(function(document) { ... })
makes it (the code, not the function) a valid expression. See here.
This:
(function(document) { ... } )(document);
calls that function with document as a parameter.
It's a basic modularization pattern. In different environments you could've passed some other object instead of document, but nothing inside that function has to know bout it.
This is called self-executed function. It evaluates the anonymous function taking a parameter called document with that parameter passed in.

Having trouble understanding this definition of javaScript function

http://jsfiddle.net/sidonaldson/ZuPYM/
(function() {
if (window.DeviceOrientationEvent)
{
$("e").innerHTML = "DeviceOrientationEvent";
window.addEventListener('deviceorientation', function(e)
{
// y-axis - yaw
var g = e.gamma || 0;
// x-axis - tilt
var b = e.beta || 0;
// z=axis - swivel
var a = e.alpha || 0;
// degree north
var c = e.compassHeading || e.webkitCompassHeading || 0;
// accuracy in deg
var accuracy = e.compassAccuracy || e.webkitCompassAccuracy || 0;
deviceOrientationHandler(g, b, a, c, accuracy);
}, false);
}
else
{
$("e").innerHTML = "NOT SUPPORTED #FAIL";
}
})();
Why does the function have a format of (function(...) {...}) (); What is going on here I have never seen a function declared like this.
Is the $ use a variable name like a _ in other languages
How does this function keep on looping, in C++ you needed a while or for or recursion what is going on with the function('e').
1) why does the function have a format of (function(...) {...}) (); What is going on here I have never seen a function declared like this.
This is a so called IIFE(Instantly Invoked Function Expression), which is basically an unnamed function which gets called just when the compiler reaches its end.
Think of it as a simple named function:
function myFunc() {...my code...}
And then it is executed right after the declaration:
myFunc();
Now the IIFE:
(function() {...my code...})();
^--------------------------^^^
Parentheses to enclose the function, the last two are to invoke the function itself
2) is the $ use a variable name like a _ in other languages
Yes it is, but in this case it is a function which simply returns the element with id e(normally it is the jQuery library, a very common one).
3) how does this function keep on looping, in C++ you needed a while or for or recursion what is going on with the function('e').
The function doesn't loop, it executes just once.
EDIT: as #Rup pointed out, you could be referring to why the handler is executed every time the event is triggered. This is possible since the window.addEventListener function adds a handler to an event(in this case deviceOrientation) which will be called every time the event is triggered. For more information please refer to this page, MDN is the best place(IMHO) to get informations about JS.
This is an IIFE. Basically, this function will execute immediately, without being explicitly called. Once you are more comfortable with javascript, I would strongly recommend you to read the link for IIFE (Immediately Invoked Function Expressions)
$ is for jQuery. It is a javascript library for HTML manipulation among other things. In javascript, $ and _ and more non-alphanumeric characters are also quite frequently used to define variables. Generally, $ stands for jQuery (but you can use it for anything else also). Similarly, _ stands for underscore.js.
This function does not "keep on looping". It is a listener. It listens to the DeviceOrientationEvent event and executes only when the device orientation changes.
It seems you are very new to javascript. I'd recommend you get some experience in JS before diving into jQuery
The format you're talking about is called immediately-invoked function expression (IIFE). It is normally used in plugin / libraries definitions to make the declared function part of window/document or extend an existing object such as jquery.
$ is for jQuery, _ is for underscore.js, but it simply depends on what argument you're passing.
the function you're referring to is executed every time the event deviceorientation is fired. This is referred in javascript as a callback or a handler.
1) This is an anonymous function being called and executed inmediately.
(function(argumentList) {
// body
})(provideArguments);
2) $ is a global variable declared by the jQuery library.
3) if you use jQuery, you can directly affect all the results of your query. The library will loop for you. This code, for example, will select all anchor tags and foreach tag will execute the addClass method, putting the class "myClassName" to the results of the "query".
$('a').addClass('myClassName');
(function(...) {...}) ();
It means the code will be executed in the page directly.
$
This is the Jquery selector. cf : http://api.jquery.com/category/selectors/
e
This is an event object. cf : http://api.jquery.com/category/events/event-object/

client side javascript function

In client side javascript, whats the difference b/w
$(function(){
....
});
and
function myFunc() {
...
}
(Could not find relevant tutorials on Google)
The first is a DOM ready handler function used in jQuery (a JavaScript library). It is executed when the DOM is fully loaded. Whereas, the second is a simply defined function with name myFunc.
You can read more about JavaScript functions in MDN:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function.
They are totally different uses of function.
The first on calls function $() with parameter function() {}.
The second defines function myFunc.
$() is a shorthand for jQuery's document.ready syntax: Documentation
Code inside a $() will run when the dom has loaded enough to be accessed/manipulated.
The second example is just a normal function declaration and creates a function named myFunc that can be called with syntax myFunc() later.

What is this unknown JavaScript syntax?

Is this jQuery code
(function(jQuery){
})(jQuery);
equivalent to
$(document).ready(function () {
});
If yes, what are the differences between the two? If not, what does the first do?
EDIT:
Thanks everybody. Most response are similar with different flavours and sample
They are not equivalent.
Your first example is an Immediately-Invoked Function Expression (IIFE). It creates a closure around locally defined variables.
Your second example specifies a function to execute when the DOM is fully loaded. It is used to ensure that all element nodes in the DOM are available before executing the enclosed code. This is also a closure.
Both examples use anonymous functions.
It is worth pointing out that it is good practice to use both of your examples, like so:
(function($){
// locally-scoped, DOM-is-NOT-Ready-code here.
$(function () {
// your locally-scoped, DOM-is-ready-code here.
});
}(jQuery)); // note that I've moved the invocation into the parens
// that contain the function. This makes JSLint happy!
Absolutely not, the first one is a self-executing anonymous function and the second is the ready handler.
(function(jQuery){
//jQuery in this scope is referencing whatever is passed-in
})(jQuery);
So, the jQuery inside of the function isn't necessarily the same jQuery outside the function. But you typically do not want to mix-n-match global variable names with local ones.
Take this example:
(function(obj) {
alert(obj);
})('Hello');
This defines a function, then immediately invokes it, passing in "Hello"
$(document).ready(function () {
});
is equivalent to this:
$(function() {
});
The first snippet is an immediately invoked anonymous function which creates a local scope:
(function() {
var x = 2;
})();
alert(x); // undefined
No. The first one isn't really doing much. Just separating any variables inside from the surrounding scope, and creating a local jQuery variable inside.
The second one passes a function that is run after the DOM is ready (in other words after the <body> has loaded).
A common equivalent to:
$(document).ready(function () {
});
is:
$(function () {
});
which does the same thing.
While this:
(function(jQuery){
})(jQuery);
is often written as:
(function($){
})(jQuery);
so that the $ variable is no longer a global variable. Useful if the global $ variable is already in use.
Not at all. The first one is a closure - a function that you create and then immediately call. However, typically you would combine the two like this:
(function($) {
// use the $ variable
$(document).ready(function(){
// ...
});
})(jQuery);
By creating the closure you are renaming "jQuery" to "$" just locally for that block of code. The reason why you use the closure syntax is so that you can use the $ variable even though it might not be defined as a jQuery object in the global scope (i.e. some JavaScript frameworks like prototype use $ as a variable).
Whenever you write a jQuery plugin you should enclose all jQuery code in this kind of closure so it doesn't interfere with any other JavaScript frameworks. If you aren't writing plugins and you don't use any other JavaScript frameworks you probably don't have to bother enclosing your code in a closure.

Categories