18.04.2016 Views

Professional JavaScript For Web Developers

javascript for learners.

javascript for learners.

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 9<br />

Can you still assign an event handler to document.body.onload? Yes, you can. The problem is that<br />

document.body doesn’t exist until the page has loaded the tag. This means that if you try to<br />

assign the event handler in the element, where it should be done, you get an error. Try it for<br />

yourself:<br />

<br />

<br />

Onload Example<br />

<br />

document.body.onload = function () {<br />

alert(“loaded”);<br />

}<br />

<br />

<br />

<br />

<br />

If you run this code, you get an error saying that document.body isn’t defined. So, it is always best to<br />

assign the onload event handler to the window object.<br />

The unload event can be handled the same way, either by assigning the event handler to the window<br />

object or by assigning it in the element. The unload event fires when you navigate from one<br />

page to another (by clicking a link or using the Back/<strong>For</strong>ward buttons) or when you close the browser<br />

window:<br />

<br />

<br />

OnUnload Example<br />

<br />

<br />

<br />

<br />

You have very short amount of time in which to execute the event handler code<br />

before the window is closed or the next page takes control, so it’s usually best to<br />

avoid using an onunload event handler. The best reason to use onunload is to dereference<br />

objects that were used on the page; any functionality more complicated than<br />

this should be avoided.<br />

The resize event<br />

At times your <strong>Web</strong> page may change depending on the size of the browser window. <strong>For</strong> this case, you<br />

can use the resize event to determine when to change these dynamic elements.<br />

Similar to the load and unload events, the event handler for the resize event must be assigned either to<br />

the window object using <strong>JavaScript</strong> code or to the element in HTML:<br />

<br />

<br />

OnResize Example<br />

288

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!