JavaScript ‘this’ and Event Handlers
Inline events
These were the first event handlers browsers supported:
<p><a id="link" href="#" onclick="EventHandler();">click me</a></p>
<script>
function EventHandler() {
console.log(this);
}
</script>
In this case, we’re simply running a function when the onclick event occurs and ‘this’ will be the global window object. We can make a minor change to our inline handler so the <a> element is passed:
<p><a id="link" href="#" onclick="return EventHandler(this);">click me</a></p>
Note that we’ve also added ‘return’. If our EventHandler returns false, the click event will be canceled.
important: Never use inline event handlers!
I’ve said this before but it needs repeating. Inline event handlers are limited, clunky, and can bulk up your HTML code. They cause maintenance complications since the invoking of the event and its handler are defined in different places. Finally, script tags must be placed at the top of your HTML rather than the bottom because an event could be called as the page is loading.
Traditional DOM0 events
Here’s our example using traditional event handling:
<p><a id="link" href="#">click me</a></p>
<script>
var link = document.getElementById("link");
link.onclick = EventHandler;
function EventHandler() {
console.log(this.id);
}
</script>
In EventHandler(), every browser sets ‘this’ to the element which fired the event — our anchor tag. It’s reliable but has a major drawback: we can only assign a single handler for each event type.
Modern DOM2 events
Finally, we have modern event handling which allows multiple handlers to be specified for the same event. Unfortunately, Microsoft and the W3C had a few differences of opinion with regard to their implementation and only IE9 supports addEventListener(). We can, however, use a little object detection to create a cross-browser event-attaching function which works in all browsers:
<p><a id="link" href="#">click me</a></p>
<script>
var link = document.getElementById("link");
AttachEvent(link, "click", EventHandler);
function AttachEvent(element, type, handler) {
if (element.addEventListener) element.addEventListener(type, handler, false);
else element.attachEvent("on"+type, handler);
}
function EventHandler(e) {
console.log(this);
}
</script>
As with DOM0, all browsers set ‘this’ to the element which fired the event … except one. Internet Explorer 8.0 and below only reference the event handler so ‘this’ is always the global window object.
Fortunately we can determine the target element from the event object instead:
function EventHandler(e) {
e = e || window.event;
var target = e.target || e.srcElement;
console.log(target);
}
Comments
Post a Comment