# Events

Listen to statechange, complete, play, pause and error on a player, and the DOM events of the element.

`player.on(type, listener)` returns a function that removes the listener. The listener gets
`{ type, player, state, fatal?, error? }`.

```js
const off = player.on("statechange", ({ state }) => console.log("now", state));
player.on("complete", ({ state }) => console.log(state, "ended"));
off();
```

Click the card, or pick a state: the log shows each event as the player sends it.

```js
import { mount } from "@rupamotion/player";

const player = mount(document.querySelector(".card-flip"));
player.play("flip");
```

| Event | When |
| - | - |
| `statechange` | A state starts: a trigger, `play(state)`, a loop back. While paused it is sent after `play`. |
| `complete` | A state with a finite end has ended. Again after a seek back in it; never for an endless one. |
| `play` | `paused` changed to false, whatever changed it. |
| `pause` | `paused` changed to true, whatever changed it. |
| `error` | `{ fatal: true, error }`: an internal error made the player inert (see [errors](/guides/errors/)). |

## Rules for listeners

- A listener that throws is reported the way an `EventTarget` reports one (`reportError`). The other listeners and the
  player go on.
- An API call made while an event is sent (for example `play` inside `statechange`) is queued and runs right after, in
  a task of its own. A listener that plays on every `statechange` cannot hang the page. The argument is still checked
  at once.
- `destroy` is not queued: the root is let go at once.

## DOM events

The root sends `rupastatechange` with `detail.state`. The `<rupa-player>` element sends `rupaready` and `rupaerror`;
see the [element reference](/reference/rupa-player-element/).
