Introduction to events
Events are things that happen in the system you are programming, which the system tells you about so your code can react to them. For example, if the user clicks a button on a webpage, you might want to react to that action by displaying an information box.
Events are fired inside the browser window, and tend to be attached to a specific item that resides in it. This might be a single element, a set of elements, the HTML document loaded in the current tab, or the entire browser window. There are many different types of events that can occur.
For example:
- The user selects, clicks, or hovers the cursor over a certain element.
- The user presses a key on the keyboard.
- The user resizes or closes the browser window.
- A web page finishes loading.
An example: handling a click event
In the following example, we have a single <button>
in the page:
<button>Change color</button>
Then we have some JavaScript. We'll look at this in more detail in the next section, but for now we can just say: it adds an event handler to the button's "click" event, and the handler reacts to the event by setting the page background to a random color:
const btn = document.querySelector("button");
function random(number) {
return Math.floor(Math.random() * (number + 1));
}
btn.addEventListener("click", () => {
const rndCol = `rgb(${random(255)} ${random(255)} ${random(255)})`;
document.body.style.backgroundColor = rndCol;
});
Using addEventListener()
As we saw in the last example, objects that can fire events have an method, and this is the recommended mechanism for adding event handlers.
Let's take a closer look at the code from the last example:
The HTML <button>
element will fire an event when the user clicks the button. So it defines an addEventListener() function, which we are calling here. We're passing in two parameters:
- the string
"click"
, to indicate that we want to listen to the click event. Buttons can fire lots of other events, such as"mouseover
" when the user moves their mouse over the button, or "keydown" when the user presses a key and the button is focused. - a function to call when the event happens. In our case, the function generates a random RGB color and sets the background-color of the page
<body>
to that color.
It is fine to make the handler function a separate named function, like this:
const btn = document.querySelector("button");
function random(number) {
return Math.floor(Math.random() * (number + 1));
}
function changeBackground() {
const rndCol = `rgb(${random(255)} ${random(255)} ${random(255)})`;
document.body.style.backgroundColor = rndCol;
}
btn.addEventListener("click", changeBackground);
Event objects
Sometimes, inside an event handler function, you'll see a parameter specified with a name such as event, evt, or e. This is called the event object, and it is automatically passed to event handlers to provide extra features and information. For example, let's rewrite our random color example again slightly:
const btn = document.querySelector("button");
function random(number) {
return Math.floor(Math.random() * (number + 1));
}
function bgChange(e) {
const rndCol = `rgb(${random(255)} ${random(255)} ${random(255)})`;
e.target.style.backgroundColor = rndCol;
console.log(e);
}
btn.addEventListener("click", bgChange);
Here you can see we are including an event object, e, in the function, and in the function setting a background color style on e.target
— which is the button itself. The target
property of the event object is always a reference to the element the event occurred upon. So, in this example, we are setting a random background color on the button, not the page.
Extra properties of event objects
Most event objects have a standard set of properties and methods available on the event object. Some event objects add extra properties that are relevant to that particular type of event. For example, the keydown
event fires when the user presses a key. Its event object is a KeyboardEvent
, which is a specialized Event
object with a key
property that tells you which key was pressed:
<input id="textBox" type="text" />
<div id="output"></div>
const textBox = document.querySelector("#textBox");
const output = document.querySelector("#output");
textBox.addEventListener("keydown", (event) => {
output.textContent = `You pressed "${event.key}".`;
});