Pass function to jQuery .ready() function - javascript

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/

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.

How to handle JS calls to methods involving jQuery outside of document.ready?

I'm having a small architectural problem for a project I'm working on. Basically I've split all the Javascript logic in various files, one of them being interface.js. Inside this file I have a lot of jQuery code inside $(document).ready() but I also have a few functions that need to be called from other JS files, such as:
function hideProgressBar() {
$('.progress').hide();
}
I have declared these functions after $(document).ready() hoping that jQuery would be loaded by the time they're executed, and in practice that actually seems to work. Is there a better way of doing this though? What are the risks?
You can call document.ready inside your function.
function hideProgressBar() {
$(function(){
$('.progress').hide();
});
}
You can also declare all your functions inside one large document.ready call.
$(function(){
window.hideProgressBar = function () {
$('.progress').hide();
};
});
Normally, however, these type of functions are events or called by jquery event which means that the document is already ready.
Try make it in pure js.
var array_el = document.getElementsByClassName('progress');
if (array_el)
{
var needed_el = array_el[0];
needed_el.style.display = 'none';
}

Passing argument to function. What's wrong?

In this jsFiddle
am I trying to pass an argument to a function, but it doesn't receive the argument or it isn't executed.
Details
JQuery
$(document).ready(function() {
function addRemove(u) {
alert(u);
}
});
Any ideas what's wrong and how to fix it?
Your function only exists within the scope of the ready event handler, you need to move function addRemove outside of the ready function.
http://jsfiddle.net/EcCTx/2/
Your code was wrapped in an onload event by jsfiddle (drop-down menu on the left). So if you add a function it won't be global, but your onclick event calls a global function by the name addRemove.
You need to define your function outside of the $(document).ready().
I haven't tested it, but my guess is this: things inside of a function can't be accessed from outside of a function. For example,
$(document).ready(function() {
function addRemove(u) {
alert(u);
}
});
console.log(addRemove); // reference error or something similar
You should define addRemove function outside of $(document).ready.
the addRemove function must be outside of $(document).ready(function(){...});
In case Davin doesn't come back, here's the answer: jsFiddle defaults to wrapping your JS in the 'onLoad' method - and we can't allow that.
http://jsfiddle.net/nqbWe/
You had no defined function called addRemove in the Fiddle!
I've added this, and removed the inline javascript calls.
See this for better way of doing it:
http://jsfiddle.net/EcCTx/6/
There is nothing specifically calling that function. In the document ready part you have the function set up, but the anchor will not call that function by itself. In this instance it will only be called when someone clicks on that link.
You could give the link a class and data attribute and use those with jQuery to have something happen on page load.

How can I call a function at the very end of document.ready

I have multiple document.ready functions on a page and I want a function to be called when all my document.ready functions have been executed. I simply want the function to be called
at the very end, after all other document.ready functions have executed.
An example of this could be that each document.ready function increments a global variable when it has been executed, and the last function needs to check the value of that variable at the very end.
Any ideas ?
This will be enough:
$(function () {
window.setTimeout(function () {
// your stuff here
}, 0);
});
This postpones the execution of your function after all other in the document ready queue are executed.
First idea (for small apps): Tidy up
You can just put everything in one $().ready() call. It might nieed refactoring, but it's the right thing to do in most cases.
Second idea: A Mediator [pattern]
Create a mediator class that will register functions and call its register() instead of $().ready(). When all functions are registered You just loop over the collection and run them in the single and only $().ready() and You have a point in code that is just after all is executed.
I am currently developing a kind of a framework for jquery applications that has a mediator. I might stick together a small version including the mediator if You're interested.
Why not just calling it after all the others ?
$(function(){
func1();
...
funcN();
functionThatNeedsToBeCalledAfter();
});
Of course you will have to cleanup your code to have only 1 place where the document ready function is used... but then your code would be more readable so it's worth it.
little hacky but might work, create a variable inside jquery scope like that
$.imDone = false
then create a function with setTimeout called after short time to lookup for the variable ser to true
var theLastFunctionToCall = function(){
alert('I m the last being called!')
}
var trigger = function(){
$.imDone?theLastFunctionToCall():window.setTimeout(trigger,10);
}
trigger();
I only recommend this when u have different $(document).ready in different big js files, but if you can refactor i sincerelly recommend an optimal solution.

How to invoke $(document).ready(function() {}) in unit testing

I'm experiencing difficulties trying to invoke document.ready( function() {}) in my unit tests. Suppose I have multiple of them in my javascript file, and one of them called inside a named function i.e.
function myFunction() {
$(document).ready(function() {
//...
});
}
How do I actually invoke them in my unit tests so I can actually test them? I'm using JsTestDriver to unit test my javascripts.
Thanks.
If it's a unit test, I'm guessing you check the function outputs when given certain inputs?
Here's my opinion:
You should prepare for the case where document.ready is called and the case where it isn't.
So your unit test should run each function twice - once to simulate a pre-ready call and one to simulate a post-ready call. That is, you should have one run-through where anything that happens on document.ready DOES run, and one run-through where it's just ignored (presumably to be called later on in the lifecycle).
EDIT:
Just reread the question and understood it a bit more. You could just override $(document).ready to do what you want it to (which is NOT to wait for the DOMLoaded event to fire, but instead to run the functions immediately). This snippet will replace the $(document).ready function with a function that does exactly that. It should run before any unit tests.
var postReady = true; // or false to ignore the function calls.
jQuery.fn.ready = function(fn)
{
if(postReady && fn) fn();
}
Example test case:
<html><head><title>whatever</title>
<script type="text/javascript" src="/JS/jquery-1.3.2.js"></script>
<script type="text/javascript">
var postReady = true; // or false to ignore the function calls.
jQuery.fn.ready = function(fn)
{
alert("We stole ready!");
if(postReady && fn) fn();
}
$(document).ready(function()
{
alert("The function is called.");
});
</script>
</head><body></body>
</html>
You know document.ready... works so just start with calling the functions within it. Ideally, if you just have an init function called by the ready function then you call one function, it does what you need, and you can continue with your tests.
You can take unit testing too far, in this case you need to ask yourself what you are testing, and why. The JQuery document.ready function works, and work well (you know this because it's been tested by many many people).
I would assume the trick would be to, instead of creating an anonymous function, naming one, and using it.
//So instead of this...
$(document).ready(function() {...});
//Do the following
$(document).ready(my_function);
Then you just test my_function and make sure that it is working. Make sure that you test the functions in the order their going to be loaded for an accurate test.
I suggest you to refactor the code. Even if you find a way to call it, it will be hard to understand for other developers.
Also (IMHO, I am not quite sure) you have to call the ready handlers even after the pages ready event was triggered, because if you "install" the ready() handler, if the document.ready event was already trigger, jquery calls that handler immediately (so it never loses that event, even if your code added a handler too late - that is, way after document.ready was still done).
Couldn't you just create a user my_on_read() event ? Or something the like?
Well, in the end, please just take care of ready() events and handlers that will be installed after the document.ready() is already done :)
Part of the answer to this question can be found here.
Below is the sample code to answer this question based on the above answer:
myFunction();
$.readyList[1]();
The index assumes that there is only 1 document.ready function in the source file. Index 0 refers to something else which I believe is info on the browser.

Categories