04.11.2015 Views

javascript

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

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

Chapter 12: Events<br />

The addHandler() and removeHandler() methods don ’ t equalize all functionality across all browsers,<br />

such as the IE scope issue, but it does allow the seamless addition and removal of event handlers.<br />

The Event Object<br />

When an event related to the DOM is fired, all of the relevant information is gathered and stored on an<br />

object called event . This object contains basic information such as the element that caused the event, the<br />

type of event that occurred, and any other data that may be relevant to the particular event. For example,<br />

an event caused by a mouse action generates information about the mouse ’ s position, whereas an event<br />

caused by a keyboard action generates information about the keys that were pressed. All browsers<br />

support the event object, though not in the same way.<br />

The DOM Event Object<br />

In DOM - compliant browsers, the event object is passed in as the sole argument to an event handler.<br />

Regardless of the method used to assign the event handler, DOM Level 0 or DOM Level 2, the event<br />

object is passed in. Here is an example:<br />

var btn = document.getElementById(“myBtn”);<br />

btn.onclick = function(event){<br />

alert(event.type); //”click”<br />

};<br />

btn.addEventListener(“click”, function(event){<br />

alert(event.type); //”click”<br />

}, false);<br />

Both event handlers in this example pop up an alert indicating the type of event being fired by using<br />

the event.type property. This property always contains the type of event that was fired, such as<br />

“ click ” (it is the same value that you pass into addEventListener() and removeEventListener() ).<br />

When an event handler is assigned using HTML attributes, the event object is available as a variable<br />

called event . Here’s an example:<br />

< input type=”button” value=”Click Me” onclick=”alert(event.type)” / ><br />

Providing the event object in this way allows HTML attribute event handlers to perform the same as<br />

JavaScript functions.<br />

The event object contains properties and methods related to the specific event that caused its<br />

creation. The available properties and methods differ based on the type of event that was fired, but all<br />

events have the members listed in the following table.<br />

375

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

Saved successfully!

Ooh no, something went wrong!