Documentation

Documentation versions (currently viewingVaadin 23)

You are viewing documentation for Vaadin 23. View latest documentation

Listening to User Events Using the Element API

Listen to any browser events.

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.

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.

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.

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 for more.

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