# 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 in some way if you want to. For example, in a web browser, events can be user actions like clicks, mouse movements, or key presses, or they can be things that happen in the browser, like a page finishing loading.

## Event Handling

You can "listen" for events and trigger a function (an "event handler") when the event occurs. There are several ways to do this:

### Inline Event Handlers (not recommended)

```html
<button onclick="alert('Button clicked!');">Click me</button>
```

This is generally considered bad practice because it mixes HTML and JavaScript.

### Event Handler Properties

```javascript
const button = document.querySelector('button');
button.onclick = function() {
  alert('Button clicked!');
};
```

This is better, but you can only have one event handler per event type on an element.

### `addEventListener()`

The modern and recommended way to handle events is using `addEventListener()`:

```javascript
const button = document.querySelector('button');

button.addEventListener('click', function() {
  alert('Button clicked!');
});
```

With `addEventListener()`, you can add multiple event handlers for the same event type on the same element.

## Common Events

*   **Mouse Events**: `click`, `dblclick`, `mousedown`, `mouseup`, `mousemove`, `mouseover`, `mouseout`, `mouseenter`, `mouseleave`
*   **Keyboard Events**: `keydown`, `keyup`, `keypress`
*   **Form Events**: `submit`, `change`, `focus`, `blur`
*   **Window/Document Events**: `load`, `unload`, `resize`, `scroll`

## The Event Object

When an event occurs, an event object is created and passed to the event handler function. This object contains information about the event, such as:

*   `type`: The type of the event (e.g., "click").
*   `target`: The element on which the event occurred.
*   `preventDefault()`: A method that can be called to prevent the default action of the event (e.g., preventing a form from submitting).
*   `stopPropagation()`: A method that can be called to stop the event from bubbling up to parent elements.
