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.
addEventListener()The modern, universally adopted method to listen for events is addEventListener:
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.
click, dblclick, mouseenter, mouseleaveinput, change, keydowninput: 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).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():
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).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?Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Changing Content and Style | Using console.log() |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.
Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.