Event Listeners
So far, we have only been able to do things by running code in the browser to get something to happen. As you hopefully have seen, the websites and apps we visit daily don't require us to write code to interact with a website.
Event listeners help us make web pages interactive. They allow your code to respond to user actions such as clicks, double clicks, or touch events.
In this section, we'll cover how to use event listeners to make your web pages dynamic and responsive to user interactions.
What is an Event Listener?
An event listener is a function that waits for an event to occur and then executes a specific block of code when that event happens. Events can be anything from clicking a button to touching the screen on a mobile device.
document.querySelector('button').addEventListener('click', function() { console.log('Button was clicked!'); });
In this example, we add an event listener to a button element. When the button is clicked, the function inside addEventListener
is executed, printing a message to the console.
Adding Event Listeners
You can add an event listener to any DOM element using the addEventListener
method. This method takes two arguments:
- The type of event (e.g.,
'click'
,'dblclick'
,'touchstart'
). - The function to execute when the event occurs.
const button = document.querySelector('button'); button.addEventListener('click', function() { alert('Button clicked!'); });
In this example, when the button is clicked, an alert box appears with the message "Button clicked!"
Using the Event Object
When an event is triggered, an event object is passed to the event listener function. This object contains useful information about the event, such as the target element, the type of event, and more:
const button = document.querySelector('button'); button.addEventListener('click', function(event) { console.log('Event type:', event.type); // Outputs: click console.log('Target element:', event.target); // Outputs: <button>...</button> });
In this example, the event
object provides information about the click event, including its type and the clicked target element.
Some Other Events
There are a massive amount of events you can listen for in the browser and to give you a flavor of some of the possibilities, I thought we should look at a few more types:
Double Click Event (dblclick
)
The badly spelt dblclick
event is triggered when an element is double-clicked. This can be useful for scenarios where you want to differentiate between single and double-click actions.
const button = document.querySelector('button'); button.addEventListener('dblclick', function(event) { alert('Button double-clicked!'); });
In this example, when the button is double-clicked, an alert box will appear with the message "Button double-clicked!".
Touch Events
Touch events are beneficial for mobile devices and tablets. They allow you to respond to user interactions such as tapping, swiping, and pinching.
touchstart
: Triggered when a touch point is placed on the touch surface.touchend
: Triggered when a touch point is removed from the touch surface.touchmove
: Triggered when a touch point is moved along the touch surface.
Example: Handling Touch Events
const box = document.querySelector('.box'); box.addEventListener('touchstart', function(event) { console.log('Touch started:', event); }); box.addEventListener('touchend', function(event) { console.log('Touch ended:', event); }); box.addEventListener('touchmove', function(event) { console.log('Touch moved:', event); });
In this example, event listeners are added to a .box
element to handle touch start, touch end, and touch move events. These events can help implement custom touch interactions like swipes.
I've created an example with all the events we covered below. Open up your mobile emulator in your dev tools and inspect the console so you can see some of the information you can get from the touch events:
Check out the code here.
Here's a list of events to explore and play with.
Practice: Using Event Listeners
- Button Click: Add a click event listener to a button that changes the button's text when clicked.
const button = document.querySelector('button'); button.addEventListener('click', function() { button.textContent = 'Clicked!'; });
- Double Click: Add a double-click event listener to a paragraph that changes its color when double-clicked.
const paragraph = document.querySelector('p'); paragraph.addEventListener('dblclick', function() { paragraph.style.color = 'red'; });
- Touch Start: Add a touchstart event listener to a div that changes its background color when touched.
const box = document.querySelector('.box'); box.addEventListener('touchstart', function() { box.style.backgroundColor = 'lightblue'; });
Event listeners will make your web pages interactive and responsive to user actions. The real fun begins here, as you can start to respond to user input.
The next section will cover event bubbling, a helpful concept to understand when handling multiple events in your apps and web pages.