Load events

The onload event

The onload event is used when the document, the window or the body are loaded into the browser. The <body> element may include images, script files, CSS files ..etc. This event can be used to check the visitor’s browser type, version, cookies situation…etc. This cannot be bubbled or cancelled.

Syntax for onload event

In HTML : <element onload=”myFunction”>

In Javascript : object.onload = myFunction(){ //code here};

Or using eventListener : object.eventListener(“load”, myFunction);

The DOMContentLoaded event

Thr DOMContentLoaded event is triggered when a document is completely loaded into a browser, i.e. the DOM is ready. However it does not wait for style sheets, images and sub-frames to complete the load. 

Example of load events

In the example below, the onload event ‘func1’ is triggered when the page is loaded, including the image. It is triggered from the HTML and when the image ‘javascript.png’ is loaded, the background color is changed to red. Its handler is an anonymous function. When window is loaded the cookie information is displayed from event listener, the DOMContentLoaded is loaded as soon as the paragraph is loaded. It does not wait for image to load.

Unload events

The onunload event 

The onunload event occurs when a page is unloaded or the window is closed. This event is also triggered when user reloads the page as well. This event can be handled by an unload event or event listener. Due to different browser settings it may not work in all browsers as well as expected.

Syntax for onunload event

In HTML : <element onunload=”myFunction”>

In Javascript : object.onunload = myFunction(){ //code here};

Or Using eventListener : object.eventListener(“unload”, myFunction);

The beforeunload event

This beforeunload event is fired when the window or the document is about to be unloaded but unloaded yet. This event allows the display of confirmation message before leaving the page. A default message appears which vary from browsers to browsers and the returnValue property can be used to create a custom message.

Syntax for beforeunload event

In HTML : <element beforeunload=”myFunction”>

In Javascript : object. beforeunload = myFunction(){ //code here};

Or Using eventListener : object.eventListener(“beforeunload”, myFunction);

Example of unload events

The example has a beforeunload event which displays an alert message when an user closes or refreshes the page. The onunload event is browser dependent and might not show up in all browsers.

 

›› go to examples ››