JavaScript Events

What Are Events?

Events are how your web page reacts to user input or system occurrences. Examples include mouse clicks, key presses, page load, and form submission.

Event Types

Here are some common event types:

  • click – mouse click
  • mouseover / mouseout – hover in and out
  • keydown, keyup – keyboard input
  • load – when the page finishes loading
  • submit – when a form is submitted
  • input, change – user input changes

Inline Event Handlers

This older approach embeds the handler directly in HTML. It's quick but not recommended for scalability.

<button onclick="alert('Clicked!')">Click me</button>

Using addEventListener

The modern and cleaner way to bind events:

const btn = document.querySelector("button");
btn.addEventListener("click", function() {
  alert("Clicked!");
});

You can add multiple listeners to the same element and separate logic from HTML.

The Event Object

Event handlers receive an object with information about the event:

document.addEventListener("keydown", function(event) {
  console.log("Key:", event.key);
  console.log("Code:", event.code);
});

This object gives access to things like event.target, event.type, and modifier keys.

Removing Event Listeners

function greet() {
  console.log("Hello");
}

btn.addEventListener("click", greet);
btn.removeEventListener("click", greet);

Only named functions can be removed. Anonymous ones can't be unregistered this way.

Best Practices

  • Use addEventListener over inline handlers
  • Use named functions to make removing them easier
  • Use event delegation (listen on parent) for dynamic content

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic