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:

`element.addEventListener(event, handler)`

**`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 ๐Ÿงช

Run these examples and interact with the elements to see the events fire.

Click Event
Output will appear here after clicking "Run".

Click the Button

Mouse Events
Output will appear here after clicking "Run".
Hover Over Me
Form Submit Event
Output will appear here after clicking "Run".

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: