Object and Onload

Summary

Learning how JavaScript works in terms of the onload event with the objects on the page and the order they are written

Things learned (from my observations):

  1. You can't work with an object if you define it before it's created on the page. Putting code at the end of the page usually gets rid of most of the problems with the page not being able to find your objects.
  2. If you have an onload event written twice on the page, it seems that only one of them will take place.
  3. If your function doesn't take need an argument, don't include the parentheses when you call it with the onload event. (onload=controlDiv1;).

Example

This example takes parts from the three process pages to show another way that both scripts can execute correctly.

This is div one. The script that controls this border is in the head tag.
This is div two. The script that controls this border is at the end of the body tag, after this div was created.

Date Created

18 Feb 2008.

Help

  1. w3schools.com

Process

Just experimenting with location (head and body) of the script and whether the function takes arguments.

  1. Only border of top box is showing.
  2. Only border of bottom box is showing.
  3. Borders of both boxes are showing.

The Code

Here’s the code. Please link back here if you’re using it.

Put this JavaScript in the head tag.

function controlDiv1(){
    var div1=document.getElementById("div1");
    div1.style.border="5px solid #ff0000";
    }
    
onload=controlDiv1;

Put this HTML in the body tag.

<div id='div1' >This is div one. The script that controls this border is in the <code>head</code> tag.</div>
<div id='div2' >This is div two. The script that controls this border is at the end of the <code>body</code> tag, after this div was created.</div>

Put this JavaScript in the body tag, after the above HTML.

function controlDiv2(){
    var div2=document.getElementById("div2");
    div2.style.border="5px solid #0000ff";
    }
    
controlDiv2();

Return to top