Javascript- Onunload Event Handler 


               


Javascript- Onunload Event Handler


Javascript



The Onunload event handler in Javascript is an event handler that is triggered when a user leaves the current web page.

When a user leaves a page that has an onunload event handler attached to it, this event handler will be triggered and can do anything that a programmer designs it to, such as create a pop-up alert, a prompt box, a command box, etc.

You'll probably seen many sales websites have this type of element. You attempt to leave the page and then an alert pop-up box springs up of a sales pitch for an item that they sell.

This is by using the unonload event handler.

As an example, try backing out of this page, or typing in a new URL to get to another page, or refreshing this page, or clicking a link on this website to get to another page. In any of these cases, the unonload event handler will be triggered and an alert pop-up box will spring up.

Note, however, that due to different browser settings, this Javascript event handler may not always work.

HTML Code

The HTML code to create a web page which creates a pop-up alert when a user tries to leave the page is:

<body onunload="window.alert('You've left the site and you haven't bought anything.');">

The onunload event handler is normally attached to the <body> tag of an HTML page. This is because the body is normally the part which is visible to a website visitor to your site.

Note that that this feature on a web page can be irritating to a user, so it should be used with discretion. This is why so many people can't stand those sales sites, because they tend to use and abuse this feature. However, during appropriate circumstances, they can enhance a website for important purposes.


Related Resources

Javascript- Onload Event Handler

Javascript- Onfocus Event Handler

Javascript- Onblur Event Handler

Javascript- Onclick Event Handler

Javascript- Onchange Event Handler

Javascript- Onkeydown Event Handler

Javascript- Onkeyup Event Handler

Javascript- Onmouseover Event Handler

Javascript- Onmousedown Event Handler

Javascript- Onmouseup Event Handler

Javascript- Onmouseout Event Handler

Javascript- Onreset Event Handler

Javascript- Onabort Event Handler

Javascript- Oncopy Event Handler



HTML Comment Box is loading comments...