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.

Cross - Browser Event Object<br />

Chapter 12: Events<br />

Although the event objects for the DOM and IE are different, there are enough similarities to allow<br />

cross - browser solutions. All of the information and capabilities of the IE event object are present in the<br />

DOM object, just in a different form. These parallels enable an easy mapping from one event model to<br />

the other. The EventUtil object described earlier can be augmented with methods that equalize the<br />

differences:<br />

var EventUtil = {<br />

};<br />

addHandler: function(element, type, handler){<br />

//code removed for printing<br />

},<br />

getEvent: function(event){<br />

return event ? event : window.event;<br />

},<br />

getTarget: function(event){<br />

return event.target || event.srcElement;<br />

},<br />

preventDefault: function(event){<br />

if (event.preventDefault){<br />

event.preventDefault();<br />

} else {<br />

event.returnValue = false;<br />

}<br />

},<br />

removeHandler: function(element, type, handler){<br />

//code removed for printing<br />

},<br />

stopPropagation: function(event){<br />

if (event.stopPropagation){<br />

event.stopPropagation();<br />

} else {<br />

event.cancelBubble = true;<br />

}<br />

}<br />

There are four new methods added to EventUtil in this code. The first is getEvent() , which returns a<br />

reference to the event object. Since the location of the event object differs in IE this method can be used<br />

to retrieve the event object regardless of the event handler assignment approach used. To use this<br />

method, you must assume that the event object is passed into the event handler and pass in that variable<br />

to the method. Here is an example:<br />

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

event = EventUtil.getEvent(event);<br />

};<br />

381

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

Saved successfully!

Ooh no, something went wrong!