Events in JavaScript notify you when something happens, like a user clicking a button or pressing a key.
To handle these events, you use event listeners. Add an event listener to any DOM element using this syntax:
Here, event-name
is the name of the event you want to listen for, and the function is the code that runs when the
event
occurs. This function is also known as the event handler.
An example for a button click:
With this code, JavaScript logs “Button is clicked” into the console whenever you click the button. This confirms that the event listener works.
Verify event listeners
To verify event listeners, use browser devtools.
- in Firefox, look for the
ev
icon in the Inspector tab. - in Chrome, use the console command
getEventListeners(element)
.
Changing the DOM with events
You can also change the DOM through events. For example, to change button and body background colors on a click, use CSS classes and add/remove them with event listeners:
First, define the required CSS classes:
Next, add an event listener to the button:
This code toggles the classes on and off each time the button is clicked, changing the background colors accordingly.
Event Object
Event listener callbacks accept an event object, often abbreviated as e
.
Here’s how you can use it:
Summary
- Event notify you of actions like clicks or key presses.
- Use
addEventListener
to handle events. - Verify listeners using browser devtools.
- Change the DOM with event listeners by toggling CSS classes.
- Event callbacks receive an event object.
- You can get a list of all available events at Mozilla Developer Network’s ( MDN) Event Reference.