18.04.2016 Views

Professional JavaScript For Web Developers

javascript for learners.

javascript for learners.

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 9<br />

One important difference in direct assignment is that subsequent assignments to the event handler wipe<br />

out the previous assignment:<br />

oDiv.onclick = fnClick;<br />

oDiv.onclick = fnDifferentClick;<br />

In this example, fnClick is assigned as the onclick event handler first, but is then replaced by<br />

fnDifferentClick.<br />

The Event Object<br />

<strong>Developers</strong> for both browsers knew that it was important to pass information about an event to the<br />

developer. The result was to create an event object that contained information specific to the event that<br />

had just occurred such as:<br />

❑<br />

❑<br />

❑<br />

The object that caused the event<br />

Information about the mouse at the time of the event<br />

Information about the keyboard at the time of the event<br />

Event objects are only created when an event occurs and are made accessible to the event handlers. After<br />

all event handlers have been executed, the event object is destroyed.<br />

As you can probably guess, Internet Explorer and the DOM implement the event object in two<br />

different ways.<br />

Locating<br />

In Internet Explorer, the event object is a property of the window object. This means that an event handler<br />

must access the event object in this way:<br />

oDiv.onclick = function () {<br />

var oEvent = window.event;<br />

}<br />

Even though it is a property of the window object, the event object is only accessible when an event<br />

occurs. After all event handlers have been executed, the event object is destroyed.<br />

The DOM standard says that the event object must be passed in as the sole argument of the event handler.<br />

So, to access the event object in a DOM-compliant browser (such as Mozilla, Safari, or Opera), you<br />

do the following:<br />

oDiv.onclick = function () {<br />

var oEvent = arguments[0];<br />

}<br />

Of course, you can also name the argument for easier access:<br />

270<br />

oDiv.onclick = function (oEvent) {<br />

}

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

Saved successfully!

Ooh no, something went wrong!