Codetainer LogoCodetainer Acad

Lessons

Lesson 23: Event Listeners

🧲 Lesson 23: DOM Event Listeners

Your website shouldn’t just sit there like a rock. It should react to what users do β€” clicks, typing, scrolling, submitting forms, and more. This is where event listeners come in.

πŸ”” What is an Event Listener?

An event listener is a function that waits for something to happen β€” like a button click β€” and then runs some code in response.

βœ… Basic Syntax


const button = document.querySelector("button");

button.addEventListener("click", function() {
  alert("Button clicked!");
});

This waits for the click event on the button. When it happens, it shows an alert.

🧠 Anatomy of addEventListener()

  • "click" – the type of event to listen for
  • function() { ... } – the code to run (the event handler)

βš™οΈ Types of Events

Here are just a few you’ll use often:

  • click – user clicks an element
  • submit – form is submitted
  • input – user types into a field
  • keydown – a key is pressed
  • mouseover – cursor hovers over an element

🎯 Named Function vs Anonymous

You can pass a named function to reuse it:


function handleClick() {
  console.log("Clicked!");
}

button.addEventListener("click", handleClick);

Or use an arrow function:


button.addEventListener("click", () => {
  console.log("Arrow function click!");
});

πŸš€ Real-World Example: Form Submit


const form = document.querySelector("form");

form.addEventListener("submit", (e) => {
  e.preventDefault(); // Prevent form from refreshing the page
  console.log("Form submitted!");
});

Notice e.preventDefault() β€” it stops the default action (e.g., reloading the page).

πŸ’‘ Best Practices

  • Use addEventListener instead of onclick – it's cleaner and more flexible
  • Always remove listeners if you're adding them repeatedly
  • Use arrow functions to avoid hoisting issues with this

You're now ready to make your website respond to clicks, form entries, key presses, and more. Next up, we’ll explore how to handle forms and user input like a boss.

CodetainerAcad