What are event listeners and how are they used?
TL;DR
Event listeners are functions that wait for specific events to occur on elements, such as clicks or key presses. They are used to execute code in response to these events. You can add an event listener to an element using the addEventListener
method. For example:
What are event listeners and how are they used?
Event listeners are a fundamental part of web development, allowing developers to make web pages interactive by responding to user actions. They are functions that wait for specific events to occur on elements, such as clicks, key presses, or mouse movements, and then execute a specified function when those events occur.
Adding an event listener
To add an event listener to an element, you use the addEventListener
method. This method takes two main arguments: the type of event to listen for and the function to execute when the event occurs.
In this example, an event listener is added to a button element with the ID myButton
. When the button is clicked, an alert box will appear with the message "Button was clicked!".
Removing an event listener
You can also remove an event listener using the removeEventListener
method. This method requires the same arguments as addEventListener
: the event type and the function to remove.
Event object
When an event listener is triggered, an event object is passed to the event handler function. This object contains useful information about the event, such as the target element, the type of event, and more.
Common event types
click
: Triggered when an element is clickedmouseover
: Triggered when the mouse pointer is moved over an elementmouseout
: Triggered when the mouse pointer is moved out of an elementkeydown
: Triggered when a key is pressed downkeyup
: Triggered when a key is released
Event delegation
Event delegation is a technique where a single event listener is added to a parent element to manage events for multiple child elements. This is useful for improving performance and managing dynamic content.
In this example, a single event listener is added to a list element. When any list item (LI
) is clicked, the event listener will handle the event.