The onunload event should be attached to the window object rather than and element of one sort of another as this is a event that will not happen with a single element, but when the whole page is unloaded. So it can be though of as the opposite of the onload event that will fire when a page has finished loading. So lets take a moment to look at a few quick examples of the onunload event in action to get a better sense as to why this event is helpful in many situations that might call for its use in a project.
This basic example of the on unload event makes use of local storage to store a time stamp when the user leaves the page. When the user returns to the page the about of time sense the last visit is displayed.
To do this I just use the get item method of the local storage to get the last time stamp if there is one. I then also get the current time, and use that to get the am9unt of time that has elapsed sense the last visit. In the event that there is not a time stamp from the last visit a value of zero is used for the amount of time. I then use get document by id to get an element by way of an id tag and then set the inner text of that element to the time value.
I am then using the on unload event to attach an event hander for the on unload event. In the body of that handler I am using the set time method of local storage to set the item that is used to get a the time stamp.
Simply put the onunload event is there to define some logic that i want to run when a user leaves a page, to go to another. There are all kinds of projects that come to mind where I wound want to do a few things before they leave, not just for my sake but for theres. For examples say i am making a game, it would be nice to have a way so that it will automatically save the state of that game when they leave the page right? Well the on unload method is there for that sort of thing.