By the end of this lesson, learners will be able to:
addEventListener() to attach events to elementsAn event is something that happens in the browser that JavaScript can respond to.
Examples of events:
JavaScript listens for these events and allows you to run specific code in response — this is called event handling.
| Event Type | Description |
|---|---|
click | Fires when an element is clicked |
input | Fires when the user types into an input field |
change | Fires when a form input changes (and loses focus) |
mouseover | Fires when the mouse pointer enters an element |
submit | Fires when a form is submitted |
addEventListener()element.addEventListener("event", function);
This tells the browser:
“When this event happens on this element, run this function.”
HTML:
<button id="greet-btn">Click Me!</button>
<p id="message">Hello!</p>
JavaScript:
let button = document.getElementById("greet-btn");
let message = document.getElementById("message");
button.addEventListener("click", function () {
message.textContent = "You clicked the button!";
});
What happens:
An event handler is the function that runs when the event occurs.
In the previous example:
function () {
message.textContent = "You clicked the button!";
}
… is the event handler function for the click event.
You can also write named functions:
function showMessage() {
message.textContent = "You clicked!";
}
button.addEventListener("click", showMessage);
✅ Best practice: Use named functions when possible to keep code clean and reusable.
HTML:
<h3 id="hover-me">Hover over me</h3>
<input id="name-input" placeholder="Type your name" />
<p id="output"></p>
JavaScript:
let heading = document.getElementById("hover-me");
let input = document.getElementById("name-input");
let output = document.getElementById("output");
heading.addEventListener("mouseover", function () {
heading.style.color = "green";
});
input.addEventListener("input", function () {
output.textContent = "You typed: " + input.value;
});
addEventListener() can be used on any DOM element"click").value to read from <input>, and .textContent to update elementsonclick="..." in HTML — keep JavaScript and HTML separateHTML:
<button id="like-btn">Like 👍</button>
<p id="likes-count">Likes: 0</p>
Task:
JavaScript:
let count = 0;
let button = document.getElementById("like-btn");
let display = document.getElementById("likes-count");
button.addEventListener("click", function () {
count++;
display.textContent = "Likes: " + count;
});