Event Listeners
Overview
Events are actions that happen in the browser (e.g., clicking a button, hovering, pressing a key on the keyboard, or submitting a form).
JavaScript can "listen" for these events using the addEventListener() method. When the specified event occurs, it executes a callback function to respond to the user.
Syntax
const btn = document.querySelector('.btn');
// addEventListener(eventType, callbackFunction)
btn.addEventListener('click', function() {
console.log('Button was clicked!');
});const input = document.querySelector('input');
// The browser automatically passes an 'Event Object' to your callback
input.addEventListener('keydown', (e) => {
// e.key tells you exactly which key was pressed!
if (e.key === 'Enter') {
console.log("Submitting search...");
}
});Common Pitfalls
- Using
element.onclick = function(){}instead ofaddEventListener. Whileonclickworks, it can only hold ONE function. If another script assigns a new function toonclick, it overwrites yours!addEventListenerallows you to attach unlimited listeners to a single event.
Interview Questions
e.preventDefault() used for?It stops the browser from performing its default action for an event. For example, submitting a <form> normally refreshes the entire page. Calling e.preventDefault() inside the submit listener stops the refresh, allowing you to handle the data with JS (like making an AJAX request instead).
Real-World Example
Preventing a form from refreshing the page, grabbing the input data, and sending it to a backend API.
form.addEventListener('submit', (e) => {
e.preventDefault();
const data = new FormData(form);
sendToAPI(data);
});Check Your Knowledge
Test your understanding of Event Listeners with these quick questions.