# addEventHandler (Shared)

> Makes a function run whenever the event happens on the given element or, with `propagate`, on any of its descendants.

- **Platform**: MY Multiplayer (MYMP)
- **Kind**: Lua Function
- **Side**: Shared
- **Category**: Events
- **URL**: https://wiki.mymp.gg/en/addEventHandler

## Syntax

```lua
bool addEventHandler(string eventName, element attachedTo, function handler [, bool propagate = true, string priority = "normal"])
```

## Parameters

| Name | Type | Description |
| --- | --- | --- |
| `eventName` | `string` | The name of a registered event (built in or made with `addEvent`). |
| `attachedTo` | `element` | The element the handler listens on. Use `root` to hear the event on any element. |
| `handler` | `function` | The function called with the event's arguments. |
| `propagate` | `bool` | Also run when the event happens on a descendant of `attachedTo`. With `false`, only when the source is `attachedTo` itself. *(default: `true`)* |
| `priority` | `string` | `"high"`, `"normal"` or `"low"`. Higher priority handlers run first; equal ones in the order they were added. *(default: `"normal"`)* |

## Returns

`true` if it was added, `false` if the event does not exist or that function is already on that event of that element.

Inside the handler, the globals `source` (where the event happened), `this` (the element the handler is attached to), `eventName`, `client` (on the server, the player who triggered a remote event) and `sourceResource` tell where the event came from. A resource's handlers are removed when it stops.

## Example

```lua
addEventHandler("onPlayerJoin", root, function()
    outputDebugString(getPlayerName(source) .. " joined")
end, true, "high")
```

### Coming from MTA

Only the names `high`, `normal` and `low` count. An adjustment such as `"high+5"` is worth the same as `"normal"`.

## See also

- [removeEventHandler (Shared)](https://wiki.mymp.gg/en/removeEventHandler.md): Takes a function off an element's event, where addEventHandler put it.
- [addEvent (Shared)](https://wiki.mymp.gg/en/addEvent.md): Registers a new event under this name. Only then can handlers be added to it and can it be triggered.
- [triggerEvent (Shared)](https://wiki.mymp.gg/en/triggerEvent.md): Triggers an event on this side, on source. The element's own handlers and its ancestors' propagating ones are called right away, before the function returns.
- [getEventHandlers (Shared)](https://wiki.mymp.gg/en/getEventHandlers.md): Lists the functions this resource put on an element's event with addEventHandler.
