JavaScript Events
Events are actions or occurrences that happen in the system you are programming, which the system tells you about so you can respond to them. They are the key to building interactive web pages.
What is an Event?
An event is a signal that something has happened. In the browser, events can be anything a user does, like clicking a button, moving their mouse over an element, or typing text. They can also be triggered by the browser itself, like a page finishing loading.
By using JavaScript, you can "listen" for these events and run a specific block of code when one occurs. This is how you make your web page respond to user actions.
The `addEventListener()` Method
The modern and most recommended way to handle events is with the `addEventListener()` method. It attaches a function to an element, and that function is executed whenever the specified event occurs on that element.
Its syntax is straightforward:
**`event`:** A string representing the event type, e.g., `'click'`, `'mouseover'`, `'keydown'`.
**`handler`:** The function (callback) to be executed when the event fires.
Practical Examples ๐งช
Click the Button
Best Practices & Next Steps ๐
Using `addEventListener()` is always better than older methods like `onclick=""` directly in your HTML. It separates JavaScript from your HTML, making your code cleaner and easier to manage.
To continue your journey with events, explore these advanced topics:
- **Event Bubbling & Capturing:** Learn how events propagate through the DOM tree.
- **Event Delegation:** A powerful technique to handle events on multiple child elements efficiently.
- **`this` and the Event Object:** A deeper dive into the information available inside an event handler.