Chapter 23. Writing Cross-Browser Event Code
The challenge in dealing with two different event models is deciding how to meld them together to make working with them as painless as possible. It's a problem that all JavaScript developers face at one point or another, and their solutions are as varied as they are. The best solutions, however, are the simplest.
In this lesson you'll look at simple solutions to cross-browser event discrepancies, and at the end of the lesson you'll add functionality to the eventUtility
object.
ACQUIRING THE EVENT TARGET
The previous two lessons detailed the differences between different types of basic event information. To acquire a reference to the element object that generated the event, standards-based browsers use the target
property, and Internet Explorer (IE) 8 and below use the srcElement
property. Despite the two very different names, both properties provide the exact same information: the element where the event was raised.
The simplest way to acquire this information is to write a function that accepts an event object as an argument and uses the appropriate property to get the event target. Such a function could look something like this:
function getTarget(event) { if (typeof event.target !== "undefined") { return event.target; } else { return event.srcElement; } }
This function, called getTarget()
, determines whether to use the target
or srcElement
property. It's a simple solution to a simple problem. Let's add a tiny bit of complexity to it so ...
Get JavaScript® 24-Hour Trainer now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.