What are event handlers/listeners?

In the simplest and most precise way:

An event handler or listener is a function to be executed when a given event occurs

From the previous Events Introduction chapter you shall be able to recall that an event is an activity on a web page like a mouse click. When an event occurs on a webpage the function that gets executed as a consequence is known as the event's handler/event's listener.

You can think of it this way: a handler is a function that handles an event.

By default every element on an HTML document has no events registered to it. The element's HTML DOM event properties, all have null assigned to them. When we register an event to an element we assign a function to act as its handler i.e the function handles the event. But why a function? Remember functions can be executed on calls - hence it makes sense to say that when the user clicks a button, call makeAlert, welcomePerson, calcScore or whatever function you have. With functions we can group code for a specific task and in this way better organise the structure of our JavaScript programs.

Handlers in action

Now that we've provided you with a decent introduction to handlers we can now go on to actually see them working. For that we'll first construct an HTML page, with a button element to be assigned an event.

<!DOCTYPE html>
<html>
    <body>
        <button>Click Me!</button>
    </body>
</html>

We'll start with, the very basic, click event which fires when a user clicks on the button and will be using its HTML DOM property onclick to assign it.

Don't worry if you can't understand onclick and other details to registering events. In the next chapter we'll solely focus on all the ways and details to assign events in JavaScript.

To register/assign a click event, or any other event, to an element (in this case button) we'll first have to select it and consequently then use the property and assign it a function.

var button = document.getElementsByTagName("button")[0];
button.onclick = function() {
    alert("Click fired!");
}

First we select button and then give it a click handler. The handler in this case is an anonymous function that has an alert call within it. We can also have named functions:

var button = document.getElementsByTagName("button")[0];
var makeAlert() {
    alert("Click fired!");
}
button.onclick = makeAlert;

Function calls can also be used if the functions return another function i.e are closures:

var button = document.getElementsByTagName("button")[0];
var assignAlert() {
    return function() { alert("Click fired!"); }
}
button.onclick = assignAlert()

Whatever the case be even handlers have to be functions that get called only when the corresponding event fires.

We can't have arrays or strings or whatever to handle events - using them doesn't even make sense! Further more an event's handler gets called when the event fires so therefore make sure you don't call your handlers before that! For the sake of an example, in the third example above the handler is not assignAlert(). We just execute it in place and get an anonymous function returned that is the handler for the click event.

Just remember which ever function is executed on an event's occurence is its handler.

Handler's argument

In the examples above, when the button element gets clicked the underlying click handler receives an object argument generated by JavaScript. Usually referred to as the event object, it contains details about the event like on which element it got fired, was the ctrl key pressed while the user clicked the button and so on, and depending on the type of event i.e mouse, keyboard, touch etc. the argument object can contain different properties and methods.

If you've done JavaScript Prototypes you will surely know the prototypal chain and protypal inheritance. This argument object, again depending on the type of event, inherits properties and methods from a chain of prototypes, of which always (as of usual) Object.prototype is at the top-most level, and Event.prototype is at the second level. All event objects will be inheriting stuff from the Event interface and some may be inherting from MouseEvent like onclick , KeyboardEvent like onkeypress, UIEvent like both onclick, onkeypress etc.

Coming back to our examples, the click handlers we constructed had no argument in their definitions so that we can directly access the event object (more on argument on JavaScript Function Arguments) We'll now add an argument and see how it all works for the onclick event.

var button = document.getElementsByTagName("button")[0];
button.onclick = function(e) {
    console.log(e);
}

Now when we click on the button, we get a MouseEvent object logged, containing more than sufficient details for us to use, that can be referred to using just e inside our handler's definition.

e is the name of our argument? You can give it any name you like - obj, eventObject or whatever suits you. However, more than often you'll see names like e, evt, event since they imply the idea of the event object in a short and yet understandable way.

Just to explore the potential of the event object consider the following example where we log the position of the mouse pointer, relative to the left and top and the viewport, where the button is clicked:

var button = document.getElementsByTagName("button")[0];
button.onclick = function(e) {
    console.log("Left: " + e.clientX);    
    console.log("Top: " + e.clientY);
}

clientX gives the position of the pointer relative to the left of the viewport and clientY relative to its top.

In conclusion

The event object is a whole world to discover, with tons of properties and methods for carrying out desired tasks. In the example above with the e argument play around with its properties and methods - try to understand what they might mean or what is their purpose and go on to write functions to see if what you thought is correct. To just give you a start, think of what does ctrlKey mean - it has got to do something with the ctrl key obviously. Maybe it shows whether the ctrl key is pressed or not. Now click the button, while holding the ctrl key and see how does the property change. This is the way to approach things while you are new to events!

In the next chapter we will be going in detail over the ways to assign events to HTML elements and some confusions involved in them. It will be all worth your time! The question is do you want to give it to it?