19.7    Handling the Events Using the Event Handler

An event handler is a JavaScript statement or function that gets executed when a specific JavaScript event is triggered (or fired). It’s relatively easy to set up an event handler for an event, and you have three options for doing so, which I’ll describe in the following three sections.

19.7.1    Setting Up an Event Handler as an HTML Attribute in the HTML Element

You’ve already seen several times in this chapter how you can set up an event handler as an HTML attribute. The principle is simple and clear, and the script can be called when the HTML document gets loaded, if the HTML element has already been loaded.

In the following line, event handler changeColor() has been set up for HTML element <button> for event onclick. This means that when the button gets clicked (onclick), function changeColor() will be called.

...
<button onclick="changeColor()">Change color</button>
...
<script src="js/script.js"></script>
...

Listing 19.24     /examples/chapter019/19_5_3/index.html

function changeColor() {
...
}

Listing 19.25     /examples/chapter019/19_5_3/js/script.js

However, the disadvantage of this method is that only one event handler can be registered. The addEventListener() method, on the other hand, can be used to register multiple event listeners.

19.7.2    Setting Up Event Handlers as a Property of an Object

To intercept the event, you need an HTML element that catches the event and assigns the event handler to this element. In practice, this could look as follows:

...
// Element which should catch the event
let element = document.querySelector('selector');
// Event to be intercepted and event handler
element.onmouseover = function() { ... };
...

Because functions are full-fledged objects in JavaScript, it’s no problem to assign them to a property as we did here.

You can write the entire process in one go as follows:

document.querySelector('selector').onmouseover = function() { ... }; 

Here’s a real-world example in which an event handler is set up as a property of an object:

...
<h1>Change HTML style</h1>
<p class="p-style">A simple paragraph text ...</p>

<button id="button01">Change color</button>
<script src="js/script.js"></script>

...

Listing 19.26     /examples/chapter019/19_7_2/index.html

document.querySelector('#button01').onclick = function() {
document.querySelector('.p-style').style.color = "navy";
document.querySelector('.p-style').style.font = "1.2em Arial";
}

Listing 19.27     /examples/chapter019/19_7_2/js/script.js

In this example, you assign a function as an event handler to an HTML element where the value of id is equal to button01 (again, the button in this case). This event handler will be executed when the button gets clicked (onclick). As an effect, the font color, size, and type of the p element are changed in this example. The event handler can be removed again using element.onclick=null;. Each object can thus be assigned only one event handler for a specific event. If you add another event handler to an event, the previous event handler will be overwritten.

19.7.3    Setting Up an Event Handler via “addEventListener()”

Similar to assigning the event handler as a property of an object, you can use the addEventListener() method to associate an HTML element with an event handler when a specific event occurs. Unlike assigning the event handler directly as a property to an object, you can use the addEventListener() method to add an event handler to an HTML element without overwriting an event you had already linked. This allows you to add multiple event handlers to an element and the same event.

Here’s an example that demonstrates the addEventListener() method:

...
<h1>Change HTML style</h1>
<p class="p-style">A simple paragraph text ...</p>

<button id="button01">Change color</button>
<script src="js/script.js"></script>

...

Listing 19.28     /examples/chapter019/19_7_3/index.html

let element = document.querySelector('#button01');
if (element) {
element.addEventListener("click", changeColor);
element.addEventListener("click", changeText);
element.addEventListener("mouseover", myborder);
element.addEventListener("mouseout", noborder);

} else {
console.log("Error: Could not set up event handler!")
}

function changeColor() {
document.querySelector('.p-style').style.color = "navy";
document.querySelector('.p-style').style.font = "1.2em Arial";
}

function changeText() {
document.querySelector('.p-style').innerHTML = "New Text";
}

function myborder() {
document.querySelector('.p-style').style.border = "1px solid black";
}

function noborder() {
document.querySelector('.p-style').style.border = "0px solid black";
}

Listing 19.29     /examples/chapter019/19_7_3/js/script.js

Admittedly, I went a bit overboard and assigned four event handlers to the HTML element with id="btton01", that is, the button. Two event handlers will be executed when the button gets clicked (click event), and one event handler will be executed each when the user keeps the mouse cursor on the button (mouseover) and when the user leaves the button again with the mouse cursor (mouseout).

You’ll notice here that the prefix on is no longer used in the addEventListener() method. For example, instead of onclick, only click is used.

Anonymous Wrapper Function

If you need an event handler with a parameter, you can write an anonymous wrapper function, for example:

...
function changeText(newTxt) {
document.querySelector('.update').innerHTML = newTxt;
}
...
let txt = "Text was changed";
element.addEventListener("click", () => {changeText(txt)});
...

Here, if the click event gets triggered at the element associated with element, you can call the changeText() function with the txt parameter inside an anonymous function.

If you want to remove an event handler from the list, you can do so by using the removeEventListener() method as follows:

...
element.removeEventListener("click", changeColor);
...