By the end of this lesson, learners will be able to:
preventDefault()
to stop default browser behaviorEvery time an event happens—like a click or a key press—JavaScript automatically passes an event object to your event handler.
This object contains information about the event:
It’s like a detailed report of what just happened.
You can give the parameter any name (though event
or e
is most common):
element.addEventListener("click", function(event) {
console.log(event); // full event object
});
Property | What It Does |
---|---|
event.type | The type of event (e.g. “click”, “keydown”) |
event.target | The element that triggered the event |
event.currentTarget | The element the listener is attached to |
event.key | The key that was pressed (for keyboard events) |
event.preventDefault() | Cancels default behavior (like form submission) |
preventDefault()
?Many HTML elements have built-in behavior:
<button type="submit">
submits the form and refreshes the page<a href="#">
jumps to the top of the pageSometimes, we want to stop this behavior so we can control it with JavaScript.
That’s what
event.preventDefault()
does.
HTML:
<form id="my-form">
<input type="text" placeholder="Your name" />
<button type="submit">Send</button>
</form>
<p id="feedback"></p>
JavaScript:
let form = document.getElementById("my-form");
let feedback = document.getElementById("feedback");
form.addEventListener("submit", function(event) {
event.preventDefault(); // stops the form from reloading the page
feedback.textContent = "Form submitted (but no reload)!";
});
Without preventDefault()
, the page would reload and the message wouldn’t appear.
HTML:
<a href="https://example.com" id="my-link">Go to Example</a>
JavaScript:
let link = document.getElementById("my-link");
link.addEventListener("click", function(event) {
event.preventDefault();
alert("Link clicked, but not navigating!");
});
event.target
vs event.currentTarget
event.target
→ the exact element that was clickedevent.currentTarget
→ the element where the listener is attachedUseful for event delegation, when many elements share one listener.
.key
in Keyboard EventsHTML:
<input id="keyboard-input" placeholder="Type something" />
<p id="key-output"></p>
JavaScript:
let input = document.getElementById("keyboard-input");
let output = document.getElementById("key-output");
input.addEventListener("keydown", function(event) {
output.textContent = "You pressed: " + event.key;
});
Concept | Description |
---|---|
event object | Holds all information about the event |
preventDefault() | Cancels default browser behavior |
event.target | The element that initiated the event |
event.key | The key that was pressed (in keyboard events) |