JavaScript ยท Chapter 15 of 55

JavaScript Events

Events are actions that happen in the browser: a click, a key press, a page load, a form submission. JavaScript can 'listen' for these events and react by running code.

The modern, recommended way to handle events is `addEventListener()`, which lets you attach multiple handlers without overwriting inline HTML attributes.

Common events

`click`, `mouseover`, `keydown`, `submit`, and `load` are among the most frequently used browser events.

addEventListener

`element.addEventListener('click', handlerFunction)` attaches a function to run whenever the event fires, and multiple listeners can coexist on the same element.

Example 1 (javascript)
document.getElementById("btn").addEventListener("click", function() {
  console.log("Button clicked!");
});
Output
Button clicked!

Runs the callback each time the button is clicked.

Example 2 (html)
<button onclick="alert('Hi!')">Say Hi</button>

Inline event handlers work but are discouraged in modern code.

Key points

  • Events represent user or browser actions.
  • addEventListener() is the modern way to attach handlers.
  • Multiple listeners can be attached to the same element.
  • Inline HTML event attributes are legacy and less flexible.
๐Ÿ’ก Note: Use `removeEventListener()` with a named function to detach a handler when it's no longer needed.

๐Ÿ“ Quick Quiz

1. Which method attaches an event handler?

2. Which event fires when a user clicks an element?

3. Can multiple listeners be attached to one element?