Handling Events: click, input, submit
Handling Events: click, input, submit
Websites become truly alive when they respond to human actions: clicking a button, typing in a text field, moving the mouse, or submitting a form. In JavaScript, these user actions are called Events, and we handle them using Event Listeners.
1. The Standard: addEventListener()
The modern, universally adopted method to listen for events is addEventListener:
Why NOT use onclick = ...?
Using .addEventListener() allows you to attach multiple independent listeners to the same element without overwriting each other, and lets you remove listeners when no longer needed.
2. Common Event Types
A. Mouse Events: click, dblclick, mouseenter, mouseleave
B. Keyboard & Input Events: input, change, keydown
input: Fires immediately on every keystroke as the user types (ideal for live search and instant character counters).change: Fires only when the user finishes and leaves the input field (loses focus).
3. Form Submission: submit and e.preventDefault()
When a user submits an HTML <form>, the browser's default behavior is to reload the entire web page and send a GET/POST HTTP request. In modern Single Page Applications (SPAs), we intercept this using e.preventDefault():
4. The Event Object (e or event)
When an event triggers, JavaScript automatically passes an Event Object to the callback function. It contains vital context:
e.target: The actual DOM element that triggered the event.e.target.value: The current value of an input element.e.key: The specific key pressed during a keyboard event (e.g.,"Enter","Escape").e.preventDefault(): Prevents default browser action (reloads, navigation).
Practice Quiz
e.preventDefault() inside a form's submit event listener?<input> field?(e) => { ... }, how do you access the current value of the text input that triggered the event?keydown event listener?Using console.log()
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Changing Content and Style | Using console.log() |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.