JavaScript 101-#19 – Getting to know JavaScript events Pt3

In the previous part we took a look at events related to forms and tried different ways to use them in projects. Even though you might have some fun by firing alert messages and pop-up windows (don’t feel bad for that), it is time to move from form to another “group” events. I am pretty sure that you will enjoy these events as well. What are we going to focus on today? The group of the day is window object events. For novices and pranksters, window object stands for body tag. Let’s dive in …

As said above, every event bound to window object will be fired whenever some interaction between user and body element of the website will happen. What kind of event will depend on the name of event below you use.

onload

The first event to examine is onload. Some people might be confused by its name and ask what exactly does that mean. Does it fires up when page is loading or right after the page is loaded? Quick answer. onload event occurs after the page is loaded. So, if you bind this event to body element, code for that event will be executed after the body and its content is completely loaded. This fact is very important. Imagine you have an element with heading, snippet of text in paragraph and a button to show whole text.

  • note: I’m not sure if I mentioned this before, but “binding” is used in events, methods and other topics to describe “connecting” to elements (dot notation). So, binding onload to body means body.onload

HTML:

<article>
  <h1>Heading of article</h1>
  <p>Short snippet of text</p>
  <button type=”button” value=”More” role=”button”>More</button>
</article>

Since the onload event is fired up after loading the page (i.e. content), you can bind it to, for example, the button and disable it for whatever reason.

JS:

// selecting the body element and binding the event to it
document.getElementsByTagName('body')[0].onload = function() {
 // selection button and disabling it
 document.getElementsByTagName('button')[0].disabled = true;
};

-note: Because getElementsByTagName() method will return and array of elements with their properties, we have to use the index in brackets to select the element we want. Otherwise, code would not work.

In case onload event would be fired before the window is loaded, JavaScript would not work at all. Why? How do you want to disable button that doesn’t even exist yet?

onunload

As an opposite to previous event we can also use onunload event. This event is fired every time the window (i.e. page) is closed, well right before it is closed. This also applies to refreshing or reloading the page. Do you know that suspicious websites showing pop-up messages when you try to close them? This might be example of onunload in action. However, there is a “good” news in the form of browser support. It looks like only IE (weird right?) and Safari support this event. Wanna example? How about an alert message on closing the page?

JS:

document.getElementsByTagName('body')[0].onunload = function() {
 alert(“See ya next time.”);
};

Previous two events were the only events related to window existing before HTML5. Since now, every next event will be a “child” of HTML5.

onbeforeunload

Another event you can use to prevent the user from closing the page is onbeforeunload (Who creates these names?). This event also fires just before the page is loaded or refreshed (reloaded) and it displays a message set as default. This message is the same as confirm() window and offers two buttons. However, you can easily override this behavior and display your own by using return command.

JS:

document.getElementsByTagName('body')[0].onbeforeunload = function() {
 return “Do you really want to go?”;
};

Unlike onunload event there is not a problem in browser support except some issues that might appear in Opera older than version 15. But who is using it anyway?

onafterprint & onbeforeprint

I don’t want to throttle you by huge amount of text (seriously) so let’s take two events at one time. These events are onafterprint and onbeforeprint. Don’t worry, we are still on the web. Print simply means printing the website, saving it as pdf or whatever do you like. As their names suggest, onbeforeprint is fired before the page is going to be printed and onafterprint after it is printed. This can be even used in a good way to inform user what is going to happen …

JS:

document.getElementsByTagName('body')[0].onbeforeprint = function() {
 alert(“The page you are viewing will be printed out.”);
};

document.getElementsByTagName('body')[0].onafterprint = function() {
 alert(“Page was printed out. You can safely continue in browsing now.”);
};

For both of these events apply only partial support across browsers. You can use them in Mozilla Firefox and – is that a joke? – IE.

ononline & onoffline

These two events are fired up when the website you are browsing is either in online or offline mode. Because of their poor support, the work only in Mozilla Firefox and IE 8 – 10, you will probably not use them as much in your work. However, interesting way to utilize these events can be to target these two specific browsers (Firefox and IE 8-10) in order to execute some JavaScript code.

JS:

document.getElementsByTagName('body')[0].ononline = function() {
 prompt(“Do you like Firefox or old IE?”);
};

onpageshow & onpagehide

Remember when we talked about onload and onunload events? Well, these are similar. The only difference here is the order in which they are fired. onpageshow is fired after the onload. So, if you use both of them, code for onload will be executed as first and code for onpageshow as second.

JS:

document.getElementsByTagName('body')[0].onload = function() {
 alert(“Page is loaded and ready!”);
};

document.getElementsByTagName('body')[0].onpageshow = function() {
 alert(“Yes we know, the page is was loaded.”);
};

onmesage & onerror

The onmessage event is fired in situation when postMessage() method is used to send some message. onerror event is fired any time when some error will occur in your script files or code on the page. This event can be very useful for debugging or refactoring your code.

onpopstate & onstorage

Every time you change the history of the window, the onpopstate event is fired. It is important to mention that this event will not fire in case of using pushState() or replaceState() methods on history object of the browser. Only user interaction with the browser (navigating through history via buttons) can trigger it. onstorage is related to Web Storage (localStorage) and it is fired every time the Web Storage is updated (some key or value is changed). WebStorage is used to store certain information in key & value pair (like JavaScript object or JSON) in user’s browser.

onresize & onhashchange

The last two events we are going to explore are onresize and onhashchange. The second event, onhashchange, is triggered when URL of the website is changed. This applies only to the part starting with hashtag “#”. The onresize event is fired (or triggered) any time you resize the window. You can use this event for example to display a pop-up message showing what the resolution is.

JS:

window.onresize = function() {
 alert(“Width of the browser is ” + window.innerWidth + “px and height is ” + window.innerHeight + “px”);
};

Summary

And this is all when it comes to events related to window object. In the next part we will continue by exploring group related to mouse. Until then, practice.

Do you have any questions, recommendations, thoughts, advice or tip you would like to share with other readers of this blog, and me? Please share it in a comment. You can also send me a mail. I would love to hear from you.

Did you like this article? Please subscribe.

Are you on social media? Let's connect! You can find me on Twitter, GitHub and Dribbble.

Alex Devero

I'm Founder/CEO of DEVERO Corporation. Entrepreneur, designer, developer. My mission and MTP is to accelerate the development of humankind through technology.

2 Comments

  1. joecamel says:

    Reblogged this on Coding, Unix & Other Hackeresque Things.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: