jQuery .ready() bug? - javascript

I'm developing a JS functions to handle it in $(document).ready(...).
These functions are in file "a.js".
In function "example(TAG_ID)" I call:
console.log( $('#anything').children().length )
OK. When I include in Application Main Javascrip file: $(document).ready(example(TAG_ID)), is returned: 0
But. When I include <script>$(document).ready(example(TAG_ID))</script> after the element whose id is TAG_ID, is returned: 7 (as it should be)
Description of jQuery.ready() function is: "Specify a function to execute when the DOM is fully loaded."
I think it is not running after the elements are fully loaded... Why?

$(document).ready(example(TAG_ID))
evaluates example(TAG_ID) immediately. As the docs you quoted say, what you want to do is pass a function to ready() for it to run when the DOM is ready, which will defer the evaluation:
$(document).ready(function() { example(TAG_ID) })

Related

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

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.

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

My $.extend does not seem to work when inside a function in javascript

I have the following code:
File 1:
$(document).ready(function () {
addDataTableExts();
}
File 2:
function addDataTableExts() {
$.extend($.fn.dataTableExt.oStdClasses, {
sWrapper: 'no-margin last-child'
}
}
This seems to work okay. I now tried to replace this with the following:
File 2:
(function () {
$.extend($.fn.dataTableExt.oStdClasses, {
sWrapper: 'no-margin last-child'
}
}
This doesn't work.
Is there some reason why it only seems to work if I do this the first way? I thought
that by changing the first line of File 2 then it would cause the code to get
executed without me calling it.
You changed the code from running in the ready event to running immediately. It seems that you are loading your datatable plugin after loading file 2, so the plugin doesn't exist yet when you try to use it.
If you put it back in the ready event, it should work:
File 2:
$(document).ready(function () {
$.extend($.fn.dataTableExt.oStdClasses, {
sWrapper: 'no-margin last-child'
}
});
Note: Events in jQuery are not exclusive, so you can have several ready event handlers in the same page without problems.
"I thought that by changing the first line of File 2 then it would cause the code to get executed without me calling it."
If you actually changed only the first line as shown then you've created a syntax error - you've added an opening ( without a closing ). But simply adding the closing ) won't cause the now anonymous function expression to be executed. If you want the code to get executed without being called from File 1 you need to add extra parentheses () on the end to actually invoke the function.
Also you had a missing closing ) after the } at the end of $.extend(..., though that was also a problem in the first version of your code (and also a problem with the document ready handler in File 1).
(function () {
$.extend($.fn.dataTableExt.oStdClasses, {
sWrapper: 'no-margin last-child'
}); // <-- add missing ); here
})(); // <-- add missing )(); here
But you don't need the containing function at all unless it also wraps other code that you don't show, because that $.extend() statement on its on doesn't have any deleterious effect on the global scope.
Finally, if you do need to run that $.extend() after the page is ready but don't want to have a dependency between your two files you can add a document ready handler directly in File 2. Multiple document ready handlers will all be executed.

Jquery syntax when calling methods

This code:
<script type="text/javascript">
someMethod1();
$(function () {
someMethod2();
});
</script>
What is the difference between these two callings? When do we do the first call, and when do we do the second call? What is the order of the method execution?
someMethod1();
This might be called before or after document is ready and it does not require jQuery. If this is at the end of your page it will be called when all control are ready but if it is in middle then it will know only controls that got rendered.
$(function () {
someMethod2();
});
This is call always after the document gets ready and all the controls are ready/rendered. This requires jQuery. You can read more about ready here. This will also help you understand the other function call.
someMethod1 is executed immediately
someMethod2 waits for the whole page to load,
including external javascript files (other scripts, or from other sites), CSS
and other resources before executing the code.
$(function () {
//run after page loads
});
Method2 sometimes comes in the form of
$(document).ready(function() {
// Handler for .ready() called.
});
For more info: http://api.jquery.com/ready/
The statements in the script block are executed in the order in which they occur. If we number the lines and insert an extra line break or two to make it easier to talk about:
1 someMethod1();
2
3 $(
4 function () {
5 someMethod2();
6 }
7 );
Line 1, someMethod1() is executed first.
Then line 3, $() is executed, where the parameter to $() is an anonymous function defined on lines 4 to 6. The $() function schedules that anonymous function to be executed later in response to the document ready event. That is, the anonymous function is not executed at that time.
Finally, when the document is ready, the anonymous function from lines 4 to 6 is executed which means line 5 someMethod2() occurs.

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.

Categories