How to retrieve the function called in an onload? - javascript

Is there a way for me to retrieve and change the value of an onload function?
i.e
i want to get the value of the onload on this tag:
<body onLoad="test();">
is there a way for me to do this?
since i need to change the function being called on certain circumstances.

Yes, you can get it from window.onload.
var func = window.onload;
Given your example, you'll get a function that looks something like this:
var func = function(event) {
test();
};
So then you can call your function whenever you need, though you won't have an event object to pass it.
func();
To change it, just do it sometime before the onload event happens:
<body onload="test();">
<script>
var func = window.onload;
alert(func); // alerts the function
if (condition_is_met) {
window.onload = function() {
/* my new func */
};
}
</script>
</body>
This will overwrite the original function with a new one. As long as you do it before the event occurs, your new function will be invoked.

Related

issue with multiple window onload

I luckily found this code on the net for continuos add on onload from a different subject completely
function myPluginLoadEvent(func) {
// assign any pre-defined functions on 'window.onload' to a variable
var oldOnLoad = window.onload;
// if there is not any function hooked to it
if (typeof window.onload != 'function') {
// you can hook your function with it
window.onload = func
} else { // someone already hooked a function
window.onload = function () {
// call the function hooked already
oldOnLoad();
// call your awesome function
func();
}
}
}
// pass the function you want to call at 'window.onload', in the function defined above
myPluginLoadEvent(func);
However, this only allow for one add on onload call. How do I loop this for multiple on load call such as for i, 1++ ?
Many thanks in advance.
The code you posted will work repeatedly. Each time it's called, oldOnLoad contains whatever was previously assigned to window.onload, which could be the result of a previous use. So it just keeps chaining all the functions.
However, the modern approach is to use addEventListener rather than assigning to window.onload.
window.addEventListener("load", func);

Add event listener of a method present in another js file

I am accessing few methods written in another js file. So i'm accessing them like this:
file1:
function minit() {
this.addval = function(val1, val2) {
return val1 + val2;
}
function autoexecute(d) {
//do something here//
//raise event//
}
};
file2:
var con = new minit();
var result = con.addval(2, 3);
/*
con.autoexecute(function(d) { //Wanna do something like this
alert(d);
});
*/
Above things are working as expected, getting result..
Now, Suppose autoexecute(d) method is invoking automatically after a time interval. How can i know if the method is executed ?
So that, I want to create an event(in file2) of autoexecute(d)(in file1).
UPDATE:
I hope this example will help you to understand the issue..
company.js //this is the main file which will be used as a reference in ui.html
function hello(personname) { //this method will invoke automatically after 1 minute..
}
ui.html
<script src="company.js"></script>
<script>
$(document).ready(function() {
function bye(personame) { //this method will be called automatically if hello method invoked.... personame is the argument passed from hello method//
alert("comany.js -> hello function is executed");
}
});
</script>
You can only do this if the functions have the same scope (global scope is the best case scenario). If the autoexecute function has local scope then you cannot to do it.
In essence, override the original function like this...
// keep a reference to the original function
var _autoexecute = autoexecute;
// override the original function with your new one
function autoexecute(d) {
alert("before autoexecute"); // fired before the original autoexecute
_autoexecute(d); // call the original autoexecute function
alert("after autoexecute"); // fired after the original autoexecute
}
Now, whenever autotexecute is called it will call your new function which can handle both before and after events, as well as calling the original function. Just remove the (horrible) alerts and replace with event handlers as required.
To my knowledge, and someone should correct me if I am wrong, there is no way (at least without some library) to detect a function being fired in javascript. Function executions do not fire an event that other functions can 'handle' in that that sense.
In your example you wanted a function to automatically fire after the other function has fired, all you need to do is call the function you want to fire at the end of the one that was "fired" in the first place. Confusing but hope this helps.
function handler(){
alert("main function was fired!");
}
function main(){
//Code of main goes here and then at the end just add:
handler();
}
Now when your "main" has finished its work it will call upon the handler function.
Regardless of where you define the handler function, which can be a different file or same file, so long as it is reachable from within the main's scope, it will be fired at the end of it. It can even be declared after main has been declared, so long as it is declared before main is fired.

The difference between creating object before/after window.onload

As below, I create a function displayMsg that displays the content of "object1.msg", which is build after onload event, but it shows undefined.
But if i put
var object1 = new testObject("Hello");
before window.onload, no matter before/after displayMsg() function, it works.
Why is that? and what is the program executing order difference between these two? Thanks...
function testObject(msg) {
this.msg = msg;
}
function displayMsg() {
document.getElementById("msgbox").innerHTML = object1.msg;
}
window.onload = function() {
var object1 = new testObject("Hello");
displayMsg();
}
You're declaring object1 inside a function, therefore it's in that function's scope, and cannot be accessed from another scope.
Try this:
function testObject(msg) {
this.msg = msg;
}
function displayMsg(object) {
document.getElementById("msgbox").innerHTML = object.msg;
}
window.onload = function() {
var object1 = new testObject("Hello");
displayMsg(object);
}
You are creating your object1 object in the scope of the window.onload function.
That means there is no object1 in your display message function.
You can try passing the object as a parameter to your displayMsg() function or just migrate your entire code into the onload function.
EDIT
Just to awnser your question of the load order: Every script that you include gets executed as soon as its loaded by the browser. Using window.onload will delay all code in that function to the point where every single script of the page is loaded. And also note that the order in wich you put scripts in your html file does matter!
The onLoad event is triggered when the page or element (You can use onLoad with DOM elements) is loaded and rendered, so the rest of the javascript code that is located inline is previously read and executed.
What probably happens with you code is that you are defining the object instance variable inside the onLoad callback, hereby the "object1" is out of the scope.
You can try with this:
var object1; // Variable is defined in the global scope
function testObject(msg) {
this.msg = msg;
}
function displayMsg() {
document.getElementById("msgbox").innerHTML = object1.msg;
}
window.onload = function() {
object1 = new testObject("Hello");
displayMsg();
}
<div id="msgbox"></div>

What is wrong with this javascript code

In the code below, I have tried to display alert when the user clicks on the document.As I have done doAlert() with parenthesis, the code runs when the document load and alerts without any events occur but if I do simply
doAlert
It seems to respond when I click the document. So, is it must that I should call function in javascript without the parenthesis or what is the idea for doing this. What if I were to pass parameter to a function.
<!doctype html>
<html>
<head>
<script>
function doAlert(){
alert("Hello");
}
function init(){
document.onclick = doAlert();
}
window.onload = init();
</script>
</head>
<body>
</body>
</html>
If foo is a function, then bar = foo will assign that function to the variable bar, but bar = foo() will immediately call the function and assign its return value to bar instead.
Event handlers work by being given a function that will be called when the event happens. If you run the function immediately then its return value needs to be a function that you want to run when the event happens (in this case the return value of both doAlert and init is undefined).
document.onclick is being set to the return of doAlert and not the doAlert function itself.
Your code should look like:
<!doctype html>
<html>
<head>
<script>
function doAlert(){
alert("Hello");
}
function init(){
document.onclick = doAlert;
}
window.onload = init;
</script>
</head>
<body>
</body>
</html>
When you call a function, you get its return value.
window.onload = init();
This runs init() and sets window.onload to its return value, undefined.
You need to set it like this:
window.onload = init;
Now window.onload is set to the function init, it won't run until it needs to.
If you want to pass parameters, like in your onClick, you can do it like this:
document.onclick = function(){
doAlert('Clicked');
};
This sets onClick to an anonymous function, that calls the functions you want. Or, you can use a closure:
function doAlert(param){
return function(){
alert(param);
};
};
document.onClick = doAlert('Hello World');
doAlert is called, onClick is set to its return value, which is a function (in this case one that alerts 'Hello World').
Functions in Javascript are objects and can be passed along like any other variable. In your case, doAlert is just a reference to a function. In order to call the function pointed by this reference, you need to use parenthesis : doAlert().
The document.onclick method is supposed to be a function reference, so you assign it a function reference like this : document.onclick = doAlert. With your syntax, you assign the result of a call to doAlert() to document.onclick, which is incorrect.
Got it ? :)

why the function call does not work this way?

This is the script that i tested when the page loads.
window.onload = initAll;
function initAll() {
document.getElementById("pTag").innerHTML = "Hello Java Script !";
}
The above script works fine till i put parenthesis like initAll() during the call. _( window.onload=initAll(); )_ . Nothing happens if use initAll() during function call. It is like the script wasn't there.
Why is it so ?
window.onload expects the value you set for it to be a function (functions are like any other object in JavaScript).
If you put parens after initAll, you actually invoke the function and set window.onload to the function's return value. Since the function does not return anything explicitly, this value is undefined. So in practice you can think of this code:
window.onload = initAll();
function initAll() {
// do something with document
}
as equivalent to this code:
var result = initAll();
window.onload = result;
function initAll() {
return null;
}
I 'm sure you can immediately see why this would not work.
Because you should not execute the function at that line, you should assign an event handler to the window object, which will be triggered/executed once the load event has fired, not the returned value of a function.
However, assigning an event handler window.onload is not recommended, because it will allow for only one handler to be attached. Consider using addEventListener.
Because you're not calling the function directly in the window.onload statement, but you're assigning a function to the onload event. The system will then automatically call your initall function when the event happens. Thats why you need the function itself (without parenthesis), and not the call (with parenthesis)
This has to do with the way Javascript works. Functions also are actually objects, like about everything in javascript.
So basically, you are assigning the "Object" initAll , which happens to be a function, to window.onload . This object is then called when the onload event is triggered, assuming it is a function.
Now, when you are putting parenthesis behind your objects name, you are basically telling it to treat that object like a function and call it. this is not the way how to assign it to a property, like the window.onload property.
window.onload = initAll;
You're binding the initAll function to the onload event of the window object. The function becomes the load handler. Now, when the load event fires at the window object, this function will be invoked.
window.onload = initAll();
You're immediately invoking the function initAll. this invocation returns undefined (in your case), and that undefined value will be assigned to window.onload. Assigning the undefined value to onevent properties obviously has no effect.
When you omit the parentheses in this call:
window.onload = initAll;
You are assigning to the window.onload event the reference value of the function initAll(). This causes the function to execute when the onload event is called because they share the same reference point. When you use the assignment like this:
window.onload = initAll();
You are assigning to the window.onload event the returned value of the function, which in this case is null.

Categories

Resources