Event listeners
Another way to add an event is by adding an event listener to an element, which can be achieved by calling the .addEventListener(event, function)
method on an element. This allows us to use the same function for more than one element instead of writing it again for each attribute.
To use the method requires specifying two inputs, where the first is an event type and the second is a function to be executed when the event occurs. The event types are easily formed from the attribute names:
Attribute name | Event type |
---|---|
onload |
"load" |
onclick |
"click" |
onmouseover |
"mouseover" |
onmouseout |
"mouseout" |
onkeydown |
"keydown" |
As you can see, an event type is formed by removing the word on
from the attribute name. It appears in the form of a string as input to addEventListener
.
Anonymous functions are very convenient to use when adding event listeners. In the example below, the variable thisButton
is a button object.
thisButton.addEventListener("click", function() {
this.textContent = "Changed";
});
Notice that the first input is "click"
(the string giving the event type) and the second input is the anonymous function, which extends over all three lines. The close parenthesis for the input pair (event, function)
is found on the third line, just before the semicolon.