Events 101
Without events and handlers, we would never be able to create slick client-side web applications. Events allow JavaScript to detect when a certain action has been performed by the user, e.g. hovering over an element, clicking a link, scrolling the page, resizing the window, dragging an object or any other activity. Your JavaScript code can register a handler function which is triggered when a particular event occurs. Most browsers pass a single object to the function which contains information about the event, i.e. what keys were pressed, the position of the cursor, etc. It’s then possible to take certain actions such as animating an element, making an Ajax call, or preventing the browser’s default action. In addition, ‘this’ may be set. You can normally expect it to be the element which fired the event, but that’s not always the case…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.
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.
link.onclick = EventHandler();
— EventHandler will be run immediately and the value returned (undefined) will be assigned to the onclick property of the #link node. It may not throw an error, but your handler will never be called when the click event occurs.
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);
}
Phew. And you wondered why jQuery became so popular!
Frequently Asked Questions (FAQs) about JavaScript Event Handlers
What is the significance of ‘this’ in JavaScript event handlers?
In JavaScript, ‘this’ is a special keyword that refers to the context in which a function is called. In the case of event handlers, ‘this’ usually refers to the HTML element that the event handler is attached to. This allows you to directly access and manipulate the element from within the event handler function. For example, if you have an event handler attached to a button, ‘this’ would refer to that button. You could then use ‘this’ to change the button’s text, color, or any other property.
How can I use ‘this’ inside an event handler?
Using ‘this’ inside an event handler is straightforward. You simply use ‘this’ as you would any other variable. However, keep in mind that ‘this’ refers to the HTML element that the event handler is attached to. Here’s an example:button.addEventListener('click', function() {
this.style.backgroundColor = 'red';
});
In this example, ‘this’ refers to the button that the event listener is attached to. When the button is clicked, its background color is changed to red.
What are the different types of events in JavaScript?
JavaScript supports a wide range of events. Some of the most common ones include ‘click’, ‘mouseover’, ‘mouseout’, ‘keydown’, ‘keyup’, ‘load’, and ‘unload’. Each of these events can be used to trigger a function when the event occurs. For example, the ‘click’ event can be used to trigger a function when a user clicks on an element.
How can I attach an event handler to an element?
You can attach an event handler to an element using the ‘addEventListener’ method. This method takes two arguments: the name of the event you want to listen for, and the function you want to run when the event occurs. Here’s an example:button.addEventListener('click', function() {
alert('Button clicked!');
});
In this example, an event listener is added to a button. When the button is clicked, an alert box will pop up with the message ‘Button clicked!’.
What is the Event object in JavaScript?
The Event object is a special object that is created when an event occurs. This object contains information about the event, such as the type of event, the target element, the time the event occurred, and more. You can access the Event object from within an event handler function. For example:button.addEventListener('click', function(event) {
console.log(event.type); // Outputs: 'click'
});
In this example, the Event object is accessed through the ‘event’ parameter of the event handler function. The type of the event is then logged to the console.
Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler.