How do you know when something is a Javascript function, and when its a jQuery function [duplicate] - javascript

Sometimes I make a function and call the function later.
Example:
function example { alert('example'); }
example(); // <-- Then call it later
Somehow, some functions cannot be called. I have to call those functions inside:
$(function() { });
What do $(function() {}); and (function() { }); mean, and what's the difference/purpose of these?

$(function() { ... });
is just jQuery short-hand for
$(document).ready(function() { ... });
What it's designed to do (amongst other things) is ensure that your function is called once all the DOM elements of the page are ready to be used.
However, I don't think that's the problem you're having - can you clarify what you mean by 'Somehow, some functions are cannot be called and I have to call those function inside' ?
Maybe post some code to show what's not working as expected ?
Edit: Re-reading your question, it could be that your function is running before the page has finished loaded, and therefore won't execute properly; putting it in $(function) would indeed fix that!

The following is a jQuery function call:
$(...);
Which is the "jQuery function." $ is a function, and $(...) is you calling that function.
The first parameter you've supplied is the following:
function() {}
The parameter is a function that you specified, and the $ function will call the supplied method when the DOM finishes loading.

It's just shorthand for $(document).ready(), as in:
$(document).ready(function() {
YOUR_CODE_HERE
});
Sometimes you have to use it because your function is running before the DOM finishes loading.
Everything is explained here: http://docs.jquery.com/Tutorials:Introducing_$(document).ready()

Some Theory
$ is the name of a function like any other name you give to a function. Anyone can create a function in JavaScript and name it $ as shown below:
$ = function() {
alert('I am in the $ function');
}
JQuery is a very famous JavaScript library and they have decided to put their entire framework inside a function named jQuery. To make it easier for people to use the framework and reduce typing the whole word jQuery every single time they want to call the function, they have also created an alias for it. That alias is $. Therefore $ is the name of a function. Within the jQuery source code, you can see this yourself:
window.jQuery = window.$ = jQuery;
Answer To Your Question
So what is $(function() { });?
Now that you know that $ is the name of the function, if you are using the jQuery library, then you are calling the function named $ and passing the argument function() {} into it. The jQuery library will call the function at the appropriate time. When is the appropriate time? According to jQuery documentation, the appropriate time is once all the DOM elements of the page are ready to be used.
The other way to accomplish this is like this:
$(document).ready(function() { });
As you can see this is more verbose so people prefer $(function() { })
So the reason why some functions cannot be called, as you have noticed, is because those functions do not exist yet. In other words the DOM has not loaded yet. But if you put them inside the function you pass to $ as an argument, the DOM is loaded by then. And thus the function has been created and ready to be used.
Another way to interpret $(function() { }) is like this:
Hey $ or jQuery, can you please call this function I am passing as an argument once the DOM has loaded?

I think you may be confusing Javascript with jQuery methods. Vanilla or plain Javascript is something like:
function example() {
}
A function of that nature can be called at any time, anywhere.
jQuery (a library built on Javascript) has built in functions that generally required the DOM to be fully rendered before being called. The syntax for when this is completed is:
$(document).ready(function() {
});
So a jQuery function, which is prefixed with the $ or the word jQuery generally is called from within that method.
$(document).ready(function() {
// Assign all list items on the page to be the color red.
// This does not work until AFTER the entire DOM is "ready", hence the $(document).ready()
$('li').css('color', 'red');
});
The pseudo-code for that block is:
When the document object model $(document) is ready .ready(), call the following function function() { }. In that function, check for all <li>'s on the page $('li') and using the jQuery method .CSS() to set the CSS property "color" to the value "red" .css('color', 'red');

This is a shortcut for $(document).ready(), which is executed when the browser has finished loading the page (meaning here, "when the DOM is available"). See http://www.learningjquery.com/2006/09/introducing-document-ready. If you are trying to call example() before the browser has finished loading the page, it may not work.

Related

Call jquery function without any particular event handler

How to use jquery functions more similar to javascript ? What i mean about that, is to call a function from script tag in html like do_something()and this will trigger the function.
I have on my jquery script file $(document).ready(function() {... } and it contains some functions with onclick handlers and others, but how to trigger function by just simply inserting name of that function in html, which can be call in some instances while processing code and loading page ?
jQuery is just a JavaScript library. Its functions are JavaScript functions. You can call them in the same way as any other JavaScript function.
Passing a function as an argument to ready just means "When the ready event fires, call this function". It's similar to setTimeout(function () { … }, 5000) only with a condition other than "after 5 seconds".
It sounds like you are having trouble with the scope that $(document).ready(function(){...}) creates;
You will want to place do_something() outside of the $(document).ready(). This will allow your DOM (in html) handlers to call it.
Also keep in mind that $(document).ready() is only used to make sure that the DOM is ready before JS tries to interact with it. If you are placing your JS in the html, the DOM will be ready by the time the functions are called.
You may want to see this question for more details:
Global javascript variable inside document.ready

Why does $($) crash my page?

Disclaimer: Do not try this at home
Why, if I am using jQuery, does $($) freeze the page?
$($) is a shortcut for $(document).ready($). So, it will run the function (when the DOM is ready or directly when this is already the case).
The function passed to .ready is passed the jQuery function for convenience (especially useful when you're in noConflict mode). So, $($) will call $ with $ as argument - and everything will happen again, which is endless recursion.
Another explanation:
You call $($).
jQuery adds the function argument ($) to an internal ready list.
Some time later, jQuery sees that the DOM is ready and thinks: "Let's call all functions in the ready list".
The only function in the ready list is $, so it calls $.
jQuery sees it should pass the $ function as the argument to those functions.
It calls $ with $ as argument.
The $ function sees a function as its argument, but because the DOM is ready, it calls the function directly (there is nothing to wait for).
The $ function is called with $ as the argument.
Everything happens again since step 7 applies.
Now this is what I call "jQueryception."
You're calling whole jQuery library within jQuery.
More information;
When you call "$" (defined as jQuery core function by jQuery library) it initializes the jQuery and tries to call the defined function if it has one. When you actually call "$($);" you'll be calling jQuery inside jQuery and it'll be calling jQuery again and again.
From jQuery 1.7.1 source code;
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
And
rootjQuery = jQuery(document);
As you can see, when you call $($); it tries to call jQuery with the name of your function and if you call it with jQuery again same thing will happen endlessly as I've explained before.
$ is an alias to the jQuery factory function.
The jQuery factory function, when passed a function as first param, runs that function at document.ready and passes jQuery as the first parameter to it.
Thus you end up with a infinite recursion starting when document.ready is reached.

Pass function to jQuery .ready() function

I am currently making use of Simon Willson's addLoadEvent function to add functions that I want to run after the load event. I ran into a problem wherein the the function I passed to the addLoadEvent function referenced a div that had not yet been loaded by the DOM and so my action (showing the div) did not do anything. When I changed to using the jQuery $(document).ready function, the div has been loaded by the DOM and I can execute actions with it (make it show up).
So, a couple questions. Why is my function being executed before the DOM has completed loaded using the above function? Is there a way to delay it? The other alternative that I can think of is passing in a function to a jquery equivalent:
function jqueryAddReadyEvent(myFunc)
{
$(document).ready(function()
{
//execute already existing functions
//add a new function to the ready event
myFunc();
}
}
When I try the above code, I get a javascript error "myFunc is not a function". Is there a way to generically pass in a function to the jquery ready function and have it execute? Equivalent to the following:
$(document).ready(function()
{
funcA();
}
$(document).ready(function()
{
funcB();
}
...//more of the same
Replaced with the following:
jQueryAddReadyEvent(funcA);
jQueryAddReadyEvent(funcB);
You can just do:
$(document).ready(myFunc);
to attach functions to the DOM ready event. Here's the fiddle: http://jsfiddle.net/padtE/
If you will require many functions to be added then I suggest you do the following:
Create an array that will old all the functions you want to call.
Add functions to that array as you please.
In the .ready(function() { ... }) call every function in that array.
You're set.
It looks correct to me. Most likely you are calling it with something not a function.
Btw you can shorten this to:
var jqueryAddReadyEvent = $(document).ready
or just use $(document).ready() directly for the same effect, as it specifically does what you want to do, run functions after the load, and is actually shorter.
$(document).ready(funcA);
$(document).ready(funcB);
function jqueryAddReadyEvent(myFunc) {
$(myFunc);
}
jqueryAddReadyEvent(function() {
alert('hello world');
});
Demo: http://jsfiddle.net/AlienWebguy/UzMLE/

jQuery document.ready vs self calling anonymous function

What is the difference between these two.
$(document).ready(function(){ ... });
(function(){ ... })();
Are these both functions called at the same time?
I know, document.ready will be triggered when the entire HTML page is rendered by the browser but what about 2nd function (self calling anonymous function). Does it wait for browser to complete rendering the page or it is called whenever it is encountered?
$(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.
(function(){...})(); will be executed as soon as it is encountered in the Javascript.
$(document).ready() will be executed once the document is loaded. $(function(){...}); is a shortcut for $(document).ready() and does the exact same thing.
The following code will be executed when the DOM (Document object model) is ready for JavaScript code to execute.
$(document).ready(function(){
// Write code here
});
The short hand for the above code is:
$(function(){
// write code here
});
The code shown below is a self-invoking anonymous JavaScript function, and will be executed as soon as
browser interprets it:
(function(){
//write code here
})(); // It is the parenthesis here that call the function.
The jQuery self-invoking function shown below, passes the global jQuery object as an argument
to function($). This enables $ to be used locally within the self-invoking function without needing
to traverse the global scope for a definition. jQuery is not the only library that makes use of $, so this
reduces potential naming conflicts.
(function($){
//some code
})(jQuery);
$(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 run after DOM is "constructed". Self-invoking functions runs instantly - if inserted into <head>, before DOM is constructed.

How should I initialize jQuery?

I have seen this (I'm also using it):
$(document).ready(function(){
// do jQuery
})
and also this (I have tried lately):
(function(){
// do jQuery
})(jQuery)
both work fine.
What is the difference of the two (except on how it looks)?
Which one is more proper to use?
The second example you show is a self executing anonymous function. Every separate JS file you use would probably benefit from using it. It provides a private scope where everything you declare with the var keyword remains inside that scope only:
(function($){
var special = "nice!";
})(jQuery);
alert(special); // would be undefined
The first example is shorthand for $(document).ready which fires when the DOM can be manipulated.
A couple cool things about it. First, you can use it inside the self executing function:
(function($){
$(function(){
// Run on DOM ready
});
// Run right away
})(jQuery);
Secondly, if all you need is a few lines in document ready, you can combine both the private scope and the DOM ready function like this:
jQuery(function($){
// $ = jQuery regardless of what it means
// outside this DOM ready function
});
The first example runs the function when the DOM tree is built.
The second example runs the function right away.
If you look closely, in the second example, there are two parentheses after the function declaration ( in this particular case, you pass in the global jQuery object as an argument to avoid conflict ), thereby immediately invoking the function
The right function to use depends on when you want the function to run.
If you want to run a function on DOMReady ( the ready event ), you can use $( document ).ready like you mentioned or the shorthand $( function() {...} ).
Otherwise, if you want to run a function immediately and have anonymous function scope, use the second example.
In addition to all the previous answers,
jQuery have three initialization methods that can be used:
The traditional method compatible with most browsers, see code:
$(document).ready(function () {
});
The short-hand method, see code:
$(function () {
});
The implicit method, see code:
$().ready(function () {
});
They all work for modern browsers and safe to use.
I always use the first. The second appears to be a way to protect against jquery being overriden. One reason you might do this is if you don't know what other scripts will be loaded on the page. If all of your stuff depends on, say, jquery 1.3, and you're in an environment where you don't control the entire page, your code could break if someone loads in jquery 1.4. Sounds ugly, but this sort of thing does happen. So you can cover your butt by creating a closure immediately after you load jquery, and holding your version of jquery inside that closure. I think that's what's going on in the second example.
Neither one actually initializes jquery. Jquery takes care of any initilazation it needs on its own. You'd still, quite likely wind up using the first example even if you were using the second, you'd just be putting the $(document).ready inside the function in your second example.
Though it's an old conversation, I want to share my way to init jQuery
;(function($, window, document) {
// Your Code Goes Here
}(window.jQuery, window, document));
By this, you can sure about that nothing can go wrong.

Categories