---
name: "up.event.onClosest"
area: "API"
kind: "JavaScript function"
parent: "up.event module"
visibility: "experimental"
url: "https://unpoly.com/api/up.event.onClosest"
---
<nav aria-label="Unpoly docs">[All docs](https://unpoly.com/index.md) · [up.event module](https://unpoly.com/api/up.event.md)</nav>

# up.event.onClosest(element, eventType, [options], callback)

**This feature is experimental**. Please [share](https://github.com/unpoly/unpoly/discussions) your experiences so we know what to keep or change.

Runs a callback when the given event is observed on the given element _or its ancestors_.

<nav aria-label="Contents">

#### Contents

- [Example](#example)
- [Parameters](#parameters)
- [Return value](#return-value)

</nav>

## Example {#example}

```js
up.event.onClosest(element, 'click', function() {
  // Someone clicked on element or its ancestors
})
```

---

## Parameters {#parameters}

### element {#element}

(required)

The element to observe with its ancestors.

Type: [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element)

### eventType {#eventType}

(required)

The event type to observe.

Type: string

### [options.layer] {#options.layer}

(optional)

Only observe ancestors in the given [layer](https://unpoly.com/api/up.layer.md).

The layer is looked up with the observed element as `{ origin }`. Pass `'origin'` to observe ancestors in the element's own layer.

By default the callback runs for any ancestor in the DOM, including the element of a parent layer.

Type: string | [up.Layer](https://unpoly.com/api/up.Layer.md)

### callback {#callback}

(required)

The callback to run.

It will be called with the observed event.

Type: Function(event)

---

## Return value {#return-value}

A function that unsubscribes the callback.

When the element is destroyed, the callback will be unsubscribed automatically.

Type: Function

