Javatpoint Logo
Javatpoint Logo

JavaScript onload

In JavaScript, this event can apply to launch a particular function when the page is fully displayed. It can also be used to verify the type and version of the visitor's browser. We can check what cookies a page uses by using the onload attribute.

In HTML, the onload attribute fires when an object has been loaded. The purpose of this attribute is to execute a script when the associated element loads.

In HTML, the onload attribute is generally used with the <body> element to execute a script once the content (including CSS files, images, scripts, etc.) of the webpage is completely loaded. It is not necessary to use it only with <body> tag, as it can be used with other HTML elements.

The difference between the document.onload and window.onload is: document.onload triggers before the loading of images and other external content. It is fired before the window.onload. While the window.onload triggers when the entire page loads, including CSS files, script files, images, etc.

Syntax

Let's understand this event by using some examples.

Example1

In this example, there is a div element with a height of 200px and a width of 200px. Here, we are using the window.onload() to change the background color, width, and height of the div element after loading the web page.

The background color is set to 'red', and width and height are set to 300px each.

Test it Now

Output

After the execution of the code and loading of the page, the output will be -

JavaScript onload

Example2

In this example, we are implementing a simple animation by using the properties of the DOM object and functions of javascript. We use the JavaScript function getElementById() for getting the DOM object and then assign that object into a global variable.

Test it Now

Output

After the successful execution of the above code, the output will be -

JavaScript onload

Now, there is an example in which we will use the HTML onload attribute and the JavaScript functions.

Example3

It is a simple example of using the HTML onload attribute with the function defined in JavaScript. In this example, the alert() function gets called whenever the document refresh.

Test it Now

Output

After the execution of the above code, the output will be -

JavaScript onload




Youtube For Videos Join Our Youtube Channel: Join Now

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA