To have a working datepicker on a field, I have to put this script inside my element
$( function() {
$( "#date_datepicker" ).datepicker( { dateFormat: "yy-mm-dd" } );
});
Removing the $( function() { makes the datepicker not work.
So does it mean that the $( function() { is the same as $(document).ready?
I'm trying to optimize my javascript codes so knowing this might help.
See the extract below from http://api.jquery.com/ready/
All three of the following syntaxes are equivalent:
$(document).ready(handler)
$().ready(handler) (this is not recommended)
$(handler)
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.
});
As can be read here
Yes, it's a shorthand version of the same thing. The $ function calls the $(document).ready function when passed a function as an argument.
If you're trying to optimise in terms of speed - both will perform pretty much equivalently, however the longer $(document).ready(handler) will be minimally faster if executed lots of times.
If you're trying to optimise in terms of file size - use a minifier.
IMO the best you can do is to 'optimise' in terms of readability and simplicity. This makes the code far easier to understand and maintain. There are tools out there to take an unoptimised version and compress and optimise for you (check out Google's closure compiler).
Yes, $( function() { and $(document).ready are same.
$( function() { works as a shorthand syntax but $(document).ready makes the code more readable.
Here is a pretty safe way to run code on ready
jQuery(function($, undefined){
// code to run onready
});
Although I personally prefer doing it like this:
(function($){ // create scope and pass specific aliased variables
$(function($, undefined){ // attach callback to run onready
// code to run onready
});
})(jQuery);
This way you can make your own bundles of functionality without fear of breaking other peoples code or having your code broken by loose variable definitions. You can also call the variables that you pass along with whatever names that you want and have code that runs no on ready, for example.
(function($){ // create scope and pass specific aliased variables
$(document).on('click', 'a[href]', function(){
// code to run when a link is clicked
});
$(window).on('load',function(){
// code to run onload
});
$(function($, undefined){ // attach callback to run onready
// code to run onready
});
})(jQuery);
Note that these are the same
$(document).bind('ready', function(){});
$(document).on('ready', function(){});
$(document).ready(function(){});
$(function(){});
And that document does not have a load event
$(document).on('load', function(){}); // will not work
note that you can also find scripts like this:
jQuery(document).ready(function(){
here the $-sign is replace by jQuery to avoid conflicts with other library's
http://docs.jquery.com/Using_jQuery_with_Other_Libraries
Are you using jQuerymobile? if so instead of using document ready use
$('#pageId').live('pageinit',function(){});
Related
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.
How do I clear out anonymous functions that are set to trigger via a jQuery document.ready() call?
For example:
<script type="text/javascript">
//some code sets a doc ready callback
$(document).ready(function ()
{
alert('ready');
});
//my attempt to prevent the callback from happening
window.onload = null;
$(document).unbind("ready");
</script>
The alert happens regardless of my attempts to circumvent it. Is there any way to do this?
You'd probably get the most appropriate answer if you described what problem you're really trying to solve.
jQuery doesn't have a publicly documented way to undo or block document.ready() handlers. If you control the code, you can use a global variable and a conditional like this:
var skipReady = false;
$(document).ready(function ()
{
if (!skipReady) {
alert('ready');
}
});
// skip the document.ready code, if it hasn't already fired
skipReady = true;
Or, if you want to hack into jQuery a bit (beyond the documented interfaces), you can do this:
$(document).ready(function() {
alert("ready");
});
// stop the ready handler
$.isReady = true;
You can see this last one work here: http://jsfiddle.net/jfriend00/ZjH2k/. This works because jQuery uses the property: $.isReady to keep track of whether it has already fired the ready handlers or not. Setting it to true makes it think it has already fired them so it won't every do it again.
This works:
$(document).bind("ready", function () { alert("hey!"); });
$(document).unbind("ready");
Seems like a bug to me - all other events in jQuery are able to be unbound. Omitting this one is inconsistent.
Not a direct answer as to the omission, but here's some related info from jQuery docs:
All three of the following syntaxes are equivalent:
$(document).ready(handler)
$().ready(handler) (this is not recommended)
$(handler)
There is also $(document).bind("ready", handler). This behaves similarly to the ready method but with one exception: If the ready event has already fired and you try to .bind("ready") the bound handler will not be executed. Ready handlers bound this way are executed after any bound by the other three methods above.
$(document).ready() is dependent on the onLoad event which is triggered by the browser meaning you can not prevent it from happening. If the alert() is determined by some condition then I would use an if/else statement to decide whether it is called.
Super old question, but came across the need to do this recently to prevent document.ready code I didn't control from running in certain instances. This can be achieved by proxying jQuery's ready function, rather like a test spy. The following will work:
var ready = $.prototype.ready;
// proxy the ready function
$.prototype.ready = function ( fn, allowed ) {
allowed = allowed || false;
if ( allowed ) {
ready.call( this, fn );
}
};
All calls to $( document ).ready will now be ignored. You can override this behaviour by passing true as the second argument: $( document ).ready( fn, true )
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.
jQuery of course requires everything to be inside
$(document).ready = function() {};
similarly, svg-web requires:
window.onsvgload = function() {};
Is there a correct, elegant way to combine these that doesn't introduce any problems?
You can just bind the functions to run on the appropriate event, like this:
$(function() { //shortcut for $(document).ready(function() {
//stuff that needs the DOM to be ready
});
$(window).bind('svgload', function() {
//SVG stuff
});
There's no harm is using both, in fact that's the appropriate usage, always use the event you need, this is no different from document.ready vs window.load when you need images ready, not just the DOM.
If it matters, svgload happens after onload in the browsers that support it as of the time of this answer, not sure if that'll be consistent when other browsers support it though.
Finally found this in the 'user manual':
$(document).ready(function() {
window.addEventListener('SVGLoad', function() {
// ready to work with SVG now
}, false);
});
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.