Key Concepts
- Event Listener: A function that waits for a specific event, like a click or mouseover, to occur.
- addEventListener: A method used to attach an event listener to an HTML element.
- Click Event: An event that occurs when an element (e.g., button, link) is clicked.
- Event Handling: The process of listening for and responding to events.
- DOM Manipulation: Modifying the structure or content of a web page using JavaScript.
Practical Steps
- Identify the Target Element: Determine the HTML element to which you want to add an event listener.
- Define the Event Listener Function: Create a JavaScript function that will execute when the event occurs.
- Get the Element Reference: Use JavaScript to obtain the target element using methods like
document.getElementById()
or document.querySelector()
.
- Add the Event Listener: Call the
addEventListener
method on the element and provide the event name (e.g., "click") and the event listener function as parameters.
Example
Consider the following HTML code:
<button id="my-button">Click Me</button>
To add an event listener that displays an alert when the button is clicked, use the following JavaScript:
// Step 3: Get the Button Element
const button = document.getElementById("my-button");
// Step 4: Add the Event Listener
button.addEventListener("click", () => {
// Step 2: Define the Event Listener Function
alert("Button Clicked!");
});