By the end of this lesson, learners will be able to:
addEventListener()
to respond to user interactionsclick
, submit
, keydown
, etc.An event listener is JavaScript code that waits for something to happen—like a user clicking a button, typing into a field, or submitting a form—and then runs a function in response.
In other words:
📣 “Hey browser, when this element is clicked (or hovered or typed into), do this!”
addEventListener()
MethodThe most common way to attach an event listener in JavaScript is:
element.addEventListener("event-type", functionToRun);
element
– the HTML element you’re listening to"event-type"
– a string (e.g. "click"
, "submit"
, "keydown"
)functionToRun
– the code that runs when the event happensHTML:
<button id="myButton">Click me</button>
JavaScript:
let button = document.getElementById("myButton");
button.addEventListener("click", function () {
alert("Button clicked!");
});
This will show a pop-up only when the button is clicked.
Event Type | Description |
---|---|
click | When the user clicks an element |
submit | When a form is submitted |
keydown | When a key is pressed down |
keyup | When a key is released |
mouseover | When the mouse hovers over an element |
input | When the user types into an input field |
element.addEventListener("click", function() {
// code to run
});
function handleClick() {
alert("Clicked!");
}
element.addEventListener("click", handleClick);
document
.keydown
EventLet’s display what key the user presses:
HTML:
<input id="type-here" placeholder="Type something..." />
<p id="output"></p>
JavaScript:
let input = document.getElementById("type-here");
let output = document.getElementById("output");
input.addEventListener("keydown", function(event) {
output.textContent = "You pressed: " + event.key;
});
Concept | Description |
---|---|
addEventListener() | Adds an event listener to an element |
click , submit , keydown | Common event types |
Function to run | Called the event handler |
Multiple listeners | Allowed per element |