root@coding-prodigies:~# โ–Š
// lesson 3 of 11 ยท 16 min

Handling events

โš‘ Report an issue with this lesson
const button = document.querySelector("#submit-btn");

button.addEventListener("click", (event) => {
  console.log("Clicked!", event.target);
});

For forms, prevent the page's default full reload so you can handle submission with JavaScript:

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

form.addEventListener("submit", (event) => {
  event.preventDefault();
  const email = form.querySelector("#email").value;
  console.log("Submitted:", email);
});

Common events: click, submit, input (fires on every keystroke), change (fires when a field loses focus after changing).

The event object your handler receives carries useful details beyond just "something happened":

  • event.target โ€” the exact element the event originated from.
  • event.key โ€” on keyboard events, which key was pressed (e.g. "Enter", "Escape").
  • event.preventDefault() โ€” stops the browser's default behavior for that event (a form reloading the page, a link navigating away).
  • event.stopPropagation() โ€” stops the event from bubbling up to parent elements, which matters once you're using event delegation (covered later in this course).

A common mistake is attaching a listener before the element exists in the page yet โ€” for example, running your script in the <head> before the body has loaded, so document.querySelector returns null and calling .addEventListener on it throws. Either place your <script> tag at the end of <body>, or wrap your setup code in a DOMContentLoaded listener:

document.addEventListener("DOMContentLoaded", () => {
  document.querySelector("#submit-btn").addEventListener("click", handleClick);
});

Another one: writing button.addEventListener("click", handleClick()) with parentheses calls handleClick immediately and passes its return value as the listener โ€” almost never what you want. Pass the function itself, not the result of calling it: button.addEventListener("click", handleClick).

Try it yourself

Exercise: Write a handleSubmit(event) function like the form submit handler in this lesson: it should log 'Submitted: ' followed by event.target.value (standing in for form.querySelector('#email').value). Call it with the fakeEvent object below.
Expected output:
Submitted: ada@example.com
javascript
Output

      
    

Run your code and get it working before marking this lesson complete.

// that was the last free lesson

8 more lessons โ€” including Project: build a live search box โ€” plus a certificate are waiting.

Unlock the full course โ€” $59.99