> Markdown version of [Listening to User Events](https://vaadin.com/docs/v24/flow/create-ui/element-api/event-listener). Section index: [llms.txt](https://vaadin.com/docs/v24/flow/llms.txt)

# Listening to User Events Using the Element API

The Element API provides the `addEventListener()` method, which you can use to listen to any browser event.

**Example**: Using the `addEventListener()` method to create a `click` event.

```java
Element helloButton = ElementFactory
        .createButton("Say hello");
helloButton.addEventListener("click", e -> {
    Element response = ElementFactory
            .createDiv("Hello!");
    getElement().appendChild(response);
});
getElement().appendChild(helloButton);
```

- Clicking the "Say hello" button in the browser sends the event to the server for processing, and a new `<div>Hello!</div>` element is added to the DOM.

## <a id="accessing-data-from-events"></a>Accessing Data from Events

You can get more information about the element or user interaction by defining the required event data on the `DomListenerRegistration` returned by the `addEventListener()` method.

**Example**: Using the `addEventData()` method to define the required event data.

```java
helloButton.addEventListener("click", this::handleClick)
    .addEventData("event.shiftKey")
    .addEventData("element.offsetWidth");

private void handleClick(DomEvent event) {
    JsonObject eventData = event.getEventData();
    boolean shiftKey = eventData
            .getBoolean("event.shiftKey");
    double width = eventData
            .getNumber("element.offsetWidth");

    String text = "Shift " + (shiftKey ? "down" : "up");
    text += " on button whose width is " + width + "px";

    Element response = ElementFactory.createDiv(text);
    getElement().appendChild(response);
}
```

- The requested event data values are sent as a JSON object from the client.

- You can retrieve the event data using the `event.getEventData()` method in the listener.

- Make sure that you use:

  - the correct getter based on the data type;

  - the same keys that were provided as parameters in the `addEventData()` method.

> **Tip:** The `filter` and `debounce` settings in the `@DomEvent` annotation can also be set through the `DomListenerRegistration` object. See [Using Events with Components](https://vaadin.com/docs/v24/flow/create-ui/creating-components/events.md) for more.

`465CAE8B-8B0D-426B-818F-1CF58A9BD034`
