What is the difference between window.onload = init(); and window.onload = init; - javascript

From what I have gathered, the former assigns the actual value of whatever that functions return statement would be to the onload property, while the latter assigns the actual function, and will run after the window has loaded. But I am still not sure. Thanks for anyone that can elaborate.

window.onload = init();
assigns the onload event to whatever is returned from the init function when it's executed. init will be executed immediately, (like, now, not when the window is done loading) and the result will be assigned to window.onload. It's unlikely you'd ever want this, but the following would be valid:
function init() {
var world = "World!";
return function () {
alert("Hello " + world);
};
}
window.onload = init();
window.onload = init;
assigns the onload event to the function init. When the onload event fires, the init function will be run.
function init() {
var world = "World!";
alert("Hello " + world);
}
window.onload = init;

window.onload = foo;
assigns the value of foo to the onload property of the window object.
window.onload = foo();
assigns the value returned by calling foo() to the onload property of the window object. Whether that value is from a return statement or not depends on foo, but it would make sense for it to return a function (which requires a return statement).
When the load event occurs, if the value of window.onload is a function reference, then window's event handler will call it.

Good answers, one more thing to add:
Browser runtimes ignore non-object (string, number, true, false, undefined, null, NaN) values set to the DOM events such as window.onload. So if you write window.onload = 10 or any of the above mentioned value-types (including the hybrid string) the event will remain null.
What is more funny that the event handlers will get any object type values, even window.onload = new Date is a pretty valid code that will prompt the current date when you log the window.onload. :) But sure nothing will happen when the window.load event fires.
So, always assign a function to any event in JavaScript.

Related

JS - Elements still null after body.onload

According to this question, by the time the body onload gets called, all of the objects in the document are in the DOM, and all the images and sub-frames have finished loading.
I have some JS that is supposed to fire at body onload but my attempts to getElementByID are returning null which makes me think it's firing earlier than I think it is.
Am I wrong in my interpretation of body.onload or am I doing something else wrong?
Here is my code:
<script type="text/javascript">
window.document.body.onload = doStuff;
function doStuff() {
var txtElement = document.getElementById("myTextField");
if (txtElement != null) {
alert(txtElement.value);
}
else {
alert("Element not found!"); //This alert is always thrown
}
}
</script>
You are actually calling the doStuff function before the DOM is loaded because you have parenthesis after the function name, which causes the function to be invoked as soon as that line is encountered.
When you register a function as a callback to an event, you just want to reference the function, not invoke it. Also, you only need to register the "page" load function to the window.
Change:
window.document.body.onload = doStuff();
to:
window.onload = doStuff;
Additionally, you should modernize your code and, instead of using an event property of an element (which only allows for one function to be stored as a callback to an event), you should use the addEventListener() method to register callback functions.
Lastly, the type attribute is no longer necessary on script tags.
<script>
window.addEventListener("load", doStuff);
function doStuff() {
var txtElement = document.getElementById("myTextField");
if (txtElement != null) {
alert(txtElement.value);
}
else {
alert("Element not found!"); //This alert is always thrown
}
}
</script>

how is window.onload working? what is difference between calling a function on it and assigning value to it

Say there is a function
function init(){
alert ('hello there')
}
window.onload = init;
Here why is't not init() but init when we are actually calling the init function when the page loads
In the last line, you are actually assigning the "init" function object to the "onload" member of the "window" object.
When a page finishes loading, the browser tries to execute whatever value is stored in the "onload" member of the window object. It is presumed that this will be a function. Your code defines a function called "init" with the specified behavior of throwing an alert message. Then it assigns this function to be the "onload" function that the browser calls when the page loads.
If you wanted to execute the "init" function yourself, you would use the "init();" syntax.

Javascript function in html body, wont work

In my document I have an onLoad function given like here in this example:
<body onLoad="display()">
In addition I added a function at the end of the document which changes some CSS properties:
<script>
window.onload = foo(), bar();
</script>
Somehow the whole thing doesn't work! I tried to add all functions at the end of the document but I don't get it, somehow they don't trigger!
That will invoke the functions, but it doesn't assign anything useful to window.onload unless your last function happens to return a function.
You need to assign a function to window.onload that will invoke your functions when the window is ready.
window.onload = function() {
foo();
bar();
};
Plus, since you're putting the script at the bottom, you probably don't need the window.onload.
<script>
foo(); bar();
</script>
</body>
You should also be aware that assigning directly to window.onload will overwrite the script assigned in the <body onLoad=...>, so you shouldn't do both. Currently, the return value of bar(); is wiping out the function that invokes display();.
Getting rid of the window.onload assignment will fix that.
In the first case, I don't see a reason why it shouldn't work, as long as display() is defined function with no errors.
In the second case, when assigning event handlers via DOM, you need to pass either a function reference (i.e. instead of foo() just foo) or wrap it in an anonymous function like so:
window.onload = function() {
foo();
}

OOP JavaScript - can't assign onclick event handler on page load

I'm trying to do a custom tabs system using JavaScript. However, in order to reuse the code I want to write it in OOP style. This what I have so far:
function Tabs()
{
this.tabArray = new Array(arguments.length);
this.tabArrayC = new Array(arguments.length);
for(i=0;i<arguments.length;i++)
{
this.tabArray[i] = arguments[i];
this.tabArrayC[i] = arguments[i]+'_content';
}
this.setClickable = setClickable;
function setClickable()
{
for(i=0;i<this.tabArray.length;i++)
{
document.getElementById(this.tabArray[i]).onclick = function()
{
alert(this.tabArray[i]);
}
}
}
}
function init()
{
tab = new Tabs('tab1','tab2','tab3','tab4');
tab.setClickable();
}
window.onload = init();
Now here's the deal. I want to assign the onclick event handler to every tab that has been passed in Tabs 'class' constructor. So later in the code when I write something like:
<div id="tab1">Tab1</div>
<div id="tab2">Tab2</div>
<div id="tab3">Tab3</div>
<div id="tab4">Tab4</div>
The code which has been set up earlier:
document.getElementById(this.tabArray[i]).onclick = function()
{
alert(this.tabArray[i]);
}
... would be executed. I hope I explained that well enough. Any ideas?
There are three issues with your setClickable function (edit: and an issue with how you're calling init):
this will have a different meaning within the event handler you're generating than you expect. (More here: You must remember this)
A closure (a function that closes over data like your i variable) has an enduring reference to the variable, not a copy of its value. So all of the handlers will see i as of when they run, not as of when they're created. (More here: Closures are not complicated)
You're not declaring i, and so you're falling prey to the Horror of Implicit Globals.
Here's one way you can address those:
function setClickable()
{
var i; // <== Declare `i`
var self = this; // <== Create a local variable for the `this` value
for(i=0;i<this.tabArray.length;i++)
{
// v=== Use a function to construct the handler
document.getElementById(this.tabArray[i]).onclick = createHandler(i);
}
function createHandler(index)
{
// This uses `self` from the outer function, which is the
// value `this` had, and `index` from the call to this
// function. The handler we're returning will always use
// the `index` that was passed into `createHandler` on the
// call that created the handler, so it's not going to change.
return function() {
alert(self.tabArray[index]);
};
}
}
...and as goreSplatter and Felix point out, this line:
window.onload = init();
...calls the init function and uses its return value to assign to onload. You mean:
window.onload = init;
...which just assigns init to the onload event.
Off-topic: You might consider using the newer "DOM2" mechanisms for attaching event handlers instead of the old "DOM0" way of using the onXYZ properties and attributes. The new way is called addEventListener, although sadly Internet Explorer has only recently added that (but it has attachEvent which is very similar). If you use a library like jQuery, Prototype, YUI, Closure, or any of several others, they'll smooth out those differences for you (and provide lots of other helpful stuff).
Problematic:
function init()
{
tab = new Tabs('tab1','tab2','tab3','tab4');
tab.setClickable();
}
window.onload = init();
In this case, window.onload will be undefined, since init() returns nothing. Surely you meant
window.onload = init;
?

does var onload mean that it should run when page is loaded

// test.js //
var testObj = {};
testObj.init = function(){
console.log('google');
}
var onload = testObj.init;
/// what does it mean, does it mean it gets executed when script loaded or what, I just can't understand it as it is not looging into console anything under Google Chrome plugin...
Think of it like giving your dog 2 names:
var spot = new Dog();
var comeHereSpot = function () { return spot; }
var comeHereBoy = comeHereSpot;
Whether you call comeHereSpot or comeHereBoy the same dog will come running.
It just means that your variable onload now points to
function(){
console.log('google');
}
onload is just the name of a local variable here.
It means that variable onload is a reference to the function testObj.init. onload() will execute the function and output 'google' to the console.
No, it only means that you assign it to a variable named onload.
Depending on the scope of the code it might actually work, if the variable name collides with the onload property of the window object. In that case a variable would not be created, but it would use the existing property instead. You should not rely on this behaviour though, you should always specify it as a property of the object:
window.onload = testObj.init;
In your code, onload is simply the name of a local variable. The var keyword declares local variables. You're setting the value of onload to testObj.init, which is a function that prints 'google' to the console.
To make it run the function on page load, set window.onload to the value of the function.
window.onload = testObj.init;
Or, better yet, use event handlers to attach an "onload" event to the window object. (To make this easier, use a JavaScript library such as jQuery, but I recommend you first learn how it all works.)
Nothing is logged because you are simply setting onload to be a pointer to the function testObj.init which only gets the function's code. To actually run it, you must call testObj.init().
More about onload…
onload is a property of an HTML element that can be set to run javascript. For example:
<html>…
… <body onload="testObj.init()"> …
…</html>
This means that when the "body" element is loaded, the function testObj.init() is run.
The "onload" property can also be attatched by javascript, as in:
window.onload=myFunction();

Categories