DOM
Events & Button Click
Respond to user actions with addEventListener.
1. Explanation
Events fire when the user (or the browser) does something — click, input, submit, keydown, scroll, load. Use element.addEventListener(type, handler) to react. The handler receives an Event object with details like event.target and event.preventDefault().
2. Example
Try it yourself
Console
Click Run to see output.
3. Expected output
output
clicked! <button id="btn">Clicked!</button>4. Common mistakes
- ✗Passing handler() instead of handler — that calls it immediately
- ✗Adding the same listener many times in a loop
- ✗Forgetting event.preventDefault() on form submit, causing page reload
5. Practice questions
- Create a counter that increments on each button click
- Toggle a CSS class on click
- Listen for keydown and log event.key