How to Use Onload in Javascript
In order to make life easier for web developers, Sun Microsystems introduced JavaScript, a client-side scripting language that is easier to implement than its predecessor Java. It is supported by nearly all the modern web browsers, thus making it immensely popular by web developers.
JavaScript has given web developers a greater degree of control on how the contents of a website load and function through the use of scripts. There are certain scripts that a web developer may want to run only after all the content of the page have been loaded. This is possible through the use of onLoad event. Such an event is triggered once web page has finished loading.
Things Required:
– Computer
– Internet connectivity
– JavaScript knowledge
Instructions
-
1
The first thing that you need to do is to define the function that you want to activate once all the contents of the web page have finished loading in the head section of the page. This function can be for anything, from a pop-up window for some sort of an advertisement, to re-directing the user to another website, initiating back-ground music, or displaying a welcome message on the screen. To specify the function, go to the head section of the page, put in the opening tag for script and then write the code for the function. Assuming that you want to re-direct the user to Google, you will be using the following code in the head section: function redirect(){window.location = "http://www.google.com/";}
-
2
Next, open the body tag and write the code for the function that you had defined in the head section. Since you want the function to be performed once the web page has finished loading all of its content, you will be adding the onLoad attribute to the code. The string should look something like “” without the quotation marks, where redirect is the name of the function or script that you had defined in the head section.