> Markdown version of [Notification](https://vaadin.com/docs/v23/components/notification). Section index: [llms.txt](https://vaadin.com/docs/v23/components/llms.txt)

# Notification

Notifications are used to provide feedback to the user. They communicate information about activities, processes, and events in the application.

`notification-basic-preview.ts`

```typescript
import { html, LitElement } from 'lit';
import '@vaadin/notification';
import { applyTheme } from 'Frontend/generated/theme';

export class Example extends LitElement {
  protected override createRenderRoot() {
    const root = super.createRenderRoot();
    // Apply custom theme (only supported if your app uses one)
    applyTheme(root);
    return root;
  }

  protected override render() {
    return html`
      <vaadin-notification-card slot="middle">
        Financial report generated
      </vaadin-notification-card>
    `;
  }
}
```

**TypeScript** — `notification-basic.ts`

```typescript
const notification = Notification.show('Financial report generated', {
  position: 'middle',
});
```

**Java** — `NotificationBasic.java`

```java
// When creating a notification using the `show` static method,
// the duration is 5-sec by default.
Notification notification = Notification
        .show("Financial report generated");
```

## <a id="theme-variants"></a>Theme Variants

### <a id="success"></a>Success

The `success` theme variant can be used to display success messages, such as when a task or operation is completed.

`notification-success-preview.ts`

```typescript
import { html, LitElement } from 'lit';
import '@vaadin/notification';
import { applyTheme } from 'Frontend/generated/theme';

export class Example extends LitElement {
  protected override createRenderRoot() {
    const root = super.createRenderRoot();
    // Apply custom theme (only supported if your app uses one)
    applyTheme(root);
    return root;
  }

  protected override render() {
    return html`
      <vaadin-notification-card theme="success" slot="middle">
        Application submitted!
      </vaadin-notification-card>
    `;
  }
}
```

**TypeScript** — `notification-success.ts`

```typescript
const notification = Notification.show('Application submitted!', {
  position: 'middle',
});
notification.setAttribute('theme', 'success');
```

**Java** — `NotificationSuccess.java`

```java
Notification notification = Notification
        .show("Application submitted!");
notification.addThemeVariants(NotificationVariant.LUMO_SUCCESS);
```

Successful operations shouldn’t routinely be declared using notifications, as these can be more distracting than useful for the user. Use success notifications only for operations whose successful completion may otherwise be difficult to discern.

### <a id="error"></a>Error

The `error` theme variant can be used to display alerts, failures, or warnings.

`notification-error-preview.ts`

```typescript
import { html, LitElement } from 'lit';
import '@vaadin/button';
import '@vaadin/horizontal-layout';
import '@vaadin/icon';
import '@vaadin/notification';
import '@vaadin/vaadin-lumo-styles/vaadin-iconset';
import { applyTheme } from 'Frontend/generated/theme';

export class Example extends LitElement {
  protected override createRenderRoot() {
    const root = super.createRenderRoot();
    // Apply custom theme (only supported if your app uses one)
    applyTheme(root);
    return root;
  }

  protected override render() {
    return html`
      <vaadin-notification-card theme="error" slot="middle">
        <vaadin-horizontal-layout theme="spacing" style="align-items: center;">
          <div>Failed to generate report</div>
          <vaadin-button theme="tertiary-inline">
            <vaadin-icon icon="lumo:cross"></vaadin-icon>
          </vaadin-button>
        </vaadin-horizontal-layout>
      </vaadin-notification-card>
    `;
  }
}
```

**TypeScript** — `notification-error.ts`

```html
<!-- The duration is set to 0-sec to prevent the notification from auto-close. -->
<vaadin-notification
  theme="error"
  duration="0"
  position="middle"
  .opened="${this.notificationOpened}"
  @opened-changed="${(e: NotificationOpenedChangedEvent) => {
    this.notificationOpened = e.detail.value;
  }}"
  ${notificationRenderer(this.renderer, [])}
></vaadin-notification>

...

renderer: NotificationLitRenderer = () => html`
  <vaadin-horizontal-layout theme="spacing" style="align-items: center;">
    <div>Failed to generate report</div>
    <vaadin-button theme="tertiary-inline" @click="${this.close}" aria-label="Close">
      <vaadin-icon icon="lumo:cross"></vaadin-icon>
    </vaadin-button>
  </vaadin-horizontal-layout>
`;
```

**Java** — `NotificationError.java`

```java
// When creating a notification using the constructor,
// the duration is 0-sec by default which means that
// the notification does not close automatically.
Notification notification = new Notification();
notification.addThemeVariants(NotificationVariant.LUMO_ERROR);

Div text = new Div(new Text("Failed to generate report"));

Button closeButton = new Button(new Icon("lumo", "cross"));
closeButton.addThemeVariants(ButtonVariant.LUMO_TERTIARY_INLINE);
closeButton.getElement().setAttribute("aria-label", "Close");
closeButton.addClickListener(event -> {
    notification.close();
});

HorizontalLayout layout = new HorizontalLayout(text, closeButton);
layout.setAlignItems(Alignment.CENTER);

notification.add(layout);
notification.open();
```

Error notifications should be persistent, and provide the user with a button that closes the notification and/or allows the user to take appropriate action.

Notifications are non-modal and can be ignored, making them inappropriate for displaying unexpected technical errors that prevent the application from functioning, or situations that require immediate user action. Use a modal [Dialog](https://vaadin.com/docs/v23/components/dialog.md) in such situations.

### <a id="primary"></a>Primary

The `primary` theme variant can be used for important informational messages and/or to draw extra attention to a notification.

`notification-primary-preview.ts`

```typescript
import { html, LitElement } from 'lit';
import '@vaadin/notification';
import { applyTheme } from 'Frontend/generated/theme';

export class Example extends LitElement {
  protected override createRenderRoot() {
    const root = super.createRenderRoot();
    // Apply custom theme (only supported if your app uses one)
    applyTheme(root);
    return root;
  }

  protected override render() {
    return html`
      <vaadin-notification-card theme="primary" slot="middle">
        New project plan available
      </vaadin-notification-card>
    `;
  }
}
```

**TypeScript** — `notification-primary.ts`

```typescript
const notification = Notification.show('New project plan available', {
  position: 'middle',
});
notification.setAttribute('theme', 'primary');
```

**Java** — `NotificationPrimary.java`

```java
Notification notification = Notification
        .show("New project plan available");
notification.addThemeVariants(NotificationVariant.LUMO_PRIMARY);
```

### <a id="contrast"></a>Contrast

A high-contrast version that improves legibility and distinguishes the notification from the rest of the UI.

`notification-contrast-preview.ts`

```typescript
import { html, LitElement } from 'lit';
import '@vaadin/notification';
import { applyTheme } from 'Frontend/generated/theme';

export class Example extends LitElement {
  protected override createRenderRoot() {
    const root = super.createRenderRoot();
    // Apply custom theme (only supported if your app uses one)
    applyTheme(root);
    return root;
  }

  protected override render() {
    return html`
      <vaadin-notification-card theme="contrast" slot="middle">
        5 tasks deleted
      </vaadin-notification-card>
    `;
  }
}
```

**TypeScript** — `notification-contrast.ts`

```typescript
const notification = Notification.show('5 tasks deleted', {
  position: 'middle',
});
notification.setAttribute('theme', 'contrast');
```

**Java** — `NotificationContrast.java`

```java
Notification notification = Notification.show("5 tasks deleted");
notification.addThemeVariants(NotificationVariant.LUMO_CONTRAST);
```

## <a id="duration"></a>Duration

By default, notifications stay on-screen for 5 seconds. The duration is in milliseconds, and should be based on content and importance:

Use short durations for notifications that have:

- short text content

- lesser importance (for example, operations that finished without errors)

- no interactive elements

Use longer durations for notifications that have:

- longer text content

- higher importance (for example, errors)

- interactive elements (for example, links or "undo" actions)

A duration of at least 5 seconds is recommended to ensure that the user has a chance to see and understand the notification.

### <a id="persistent-notifications"></a>Persistent Notifications

Setting the duration to zero disables auto-closing, keeping the notification visible until explicitly dismissed by the user. This should be used for notifications that provide vital information to the user, such as errors. Persistent notifications should contain a Button that closes the notification and/or allows the user to take appropriate action.

Less-important notifications shouldn’t be persistent, and instead disappear automatically after an appropriate delay.

## <a id="position"></a>Position

Notifications can be positioned in the viewport in seven non-stretched positions, or stretched across the top or bottom:

Use the `position` attribute in HTML templates, for example `<vaadin-notification position="top-end"></vaadin-notification>`.

**TypeScript** — `notification-position.ts`

```typescript
protected override render() {
  return html`
    <vaadin-button @click="${this.show}">top-stretch</vaadin-button>
    <vaadin-button @click="${this.show}">top-start</vaadin-button>
    <vaadin-button @click="${this.show}">top-center</vaadin-button>
    <vaadin-button @click="${this.show}">top-end</vaadin-button>
    <vaadin-button @click="${this.show}">middle</vaadin-button>
    <vaadin-button @click="${this.show}">bottom-start</vaadin-button>
    <vaadin-button @click="${this.show}">bottom-center</vaadin-button>
    <vaadin-button @click="${this.show}">bottom-end</vaadin-button>
    <vaadin-button @click="${this.show}">bottom-stretch</vaadin-button>
  `;
}

show(event: MouseEvent) {
  // Use the button label as the location
  const position = (event.target as HTMLElement).textContent as NotificationPosition;

  Notification.show(position, { position });
}
```

**Java** — `NotificationPosition.java`

```java
add(createButton(Position.TOP_STRETCH),
        createButton(Position.TOP_START),
        createButton(Position.TOP_CENTER),
        createButton(Position.TOP_END), createButton(Position.MIDDLE),
        createButton(Position.BOTTOM_START),
        createButton(Position.BOTTOM_CENTER),
        createButton(Position.BOTTOM_END),
        createButton(Position.BOTTOM_STRETCH));

...

private Button createButton(Notification.Position position) {
    Button button = new Button(position.getClientName());
    button.addClickListener(event -> show(position));
    return button;
}

...

private void show(Notification.Position position) {
    Notification.show(position.getClientName(), 5000, position);
}
```

`notification-position-example.css`

```css
```

### <a id="recommendations"></a>Recommendations

- **Top End** or **Bottom Start** are recommended for most notifications, as these are unobtrusive, but still noticeable.

- **Middle** is the most disruptive position, and should be used only for important notifications, such as errors.

- **Bottom End** is the least obtrusive position, but can go unnoticed.

- **Stretch** notifications, which span the full width of the viewport, are more disruptive, and should be reserved for important notifications whose contents require more space.

- Applications with a notification button or drop-down in the header or footer should position notifications to appear in the same part of the screen.

- For a consistent user experience, use one or two positions throughout the application.

- Avoid using positions that may obstruct important parts of the UI, such as navigation.

> **Note: The Flow styling issue**
>
> The Flow notification component renders rich content via an intermediate `<flow-component-renderer>` element. This can prevent notification content from using the full width when using top stretch or bottom stretch positioning. To work around this issue, add the following CSS rule to a global style sheet:
>
> ```css
> vaadin-notification-card flow-component-renderer,
> vaadin-notification-card flow-component-renderer > div {
>   display: contents;
> }
> ```
>
> See [Vaadin Flow Components issue 1876](https://github.com/vaadin/flow-components/issues/1876).

## <a id="stacking"></a>Stacking

Multiple simultaneously displayed notifications are stacked vertically, depending on their positioning:

- When using the bottom half of the screen as the position, a new notification appears below the older notifications.

- With the position set to the top half, a new notification appears above the existing notifications.

## <a id="size"></a>Size

The notification card is automatically sized based on its content.

- In large viewports, the card’s maximum width is one-third of the viewport.

- In small viewports, the card always takes up the entire width of the viewport.

## <a id="interactive-elements"></a>Interactive Elements

Notifications can contain interactive content, such as Buttons or links that allow the user to perform related actions.

For example, if an operation fails, the error notification could offer the user the opportunity to try again. Or it could contain a link to a view that allows the user to resolve the problem.

`notification-retry-preview.ts`

```typescript
import { html, LitElement } from 'lit';
import '@vaadin/button';
import '@vaadin/horizontal-layout';
import '@vaadin/icon';
import '@vaadin/notification';
import '@vaadin/vaadin-lumo-styles/vaadin-iconset';
import { applyTheme } from 'Frontend/generated/theme';

export class Example extends LitElement {
  protected override createRenderRoot() {
    const root = super.createRenderRoot();
    // Apply custom theme (only supported if your app uses one)
    applyTheme(root);
    return root;
  }

  protected override render() {
    return html`
      <vaadin-notification-card theme="error" slot="middle">
        <vaadin-horizontal-layout theme="spacing" style="align-items: center;">
          <div>Failed to generate report</div>
          <vaadin-button theme="tertiary-inline" style="margin-left: var(--lumo-space-xl);">
            Retry
          </vaadin-button>
          <vaadin-button theme="tertiary-inline" aria-label="Close">
            <vaadin-icon icon="lumo:cross"></vaadin-icon>
          </vaadin-button>
        </vaadin-horizontal-layout>
      </vaadin-notification-card>
    `;
  }
}
```

**TypeScript** — `notification-retry.ts`

```html
<!-- The duration is set to 0-sec to prevent the notification from auto-close. -->
<vaadin-notification
  theme="error"
  duration="0"
  position="middle"
  .opened="${this.notificationOpened}"
  @opened-changed="${(e: NotificationOpenedChangedEvent) => {
    this.notificationOpened = e.detail.value;
  }}"
  ${notificationRenderer(this.renderer, [])}
></vaadin-notification>

...

renderer: NotificationLitRenderer = () => html`
  <vaadin-horizontal-layout theme="spacing" style="align-items: center;">
    <div>Failed to generate report</div>
    <vaadin-button
      theme="tertiary-inline"
      style="margin-left: var(--lumo-space-xl);"
      @click="${this.close}"
    >
      Retry
    </vaadin-button>
    <vaadin-button theme="tertiary-inline icon" @click="${this.close}" aria-label="Close">
      <vaadin-icon icon="lumo:cross"></vaadin-icon>
    </vaadin-button>
  </vaadin-horizontal-layout>
`;
```

**Java** — `NotificationRetry.java`

```java
// When creating a notification using the constructor,
// the duration is 0-sec by default which means that
// the notification does not close automatically.
Notification notification = new Notification();
notification.addThemeVariants(NotificationVariant.LUMO_ERROR);

Div statusText = new Div(new Text("Failed to generate report"));

Button retryButton = new Button("Retry");
retryButton.addThemeVariants(ButtonVariant.LUMO_TERTIARY_INLINE);
retryButton.getElement().getStyle().set("margin-left",
        "var(--lumo-space-xl)");
retryButton.addClickListener(event -> {
    notification.close();
});

Button closeButton = new Button(new Icon("lumo", "cross"));
closeButton.addThemeVariants(ButtonVariant.LUMO_TERTIARY_INLINE);
closeButton.getElement().setAttribute("aria-label", "Close");
closeButton.addClickListener(event -> {
    notification.close();
});

HorizontalLayout layout = new HorizontalLayout(statusText, retryButton,
        closeButton);
layout.setAlignItems(Alignment.CENTER);

notification.add(layout);
notification.open();
```

In situations where the user might want to revert an action, display an "undo" button.

`notification-undo-preview.ts`

```typescript
import { html, LitElement } from 'lit';
import '@vaadin/button';
import '@vaadin/horizontal-layout';
import '@vaadin/icon';
import '@vaadin/notification';
import '@vaadin/vaadin-lumo-styles/vaadin-iconset';
import { applyTheme } from 'Frontend/generated/theme';

export class Example extends LitElement {
  protected override createRenderRoot() {
    const root = super.createRenderRoot();
    // Apply custom theme (only supported if your app uses one)
    applyTheme(root);
    return root;
  }

  protected override render() {
    return html`
      <vaadin-notification-card theme="contrast" slot="middle">
        <vaadin-horizontal-layout theme="spacing" style="align-items: center;">
          <div>5 tasks deleted</div>
          <vaadin-button theme="tertiary-inline" style="margin-left: var(--lumo-space-xl);">
            Undo
          </vaadin-button>
          <vaadin-button theme="tertiary-inline" aria-label="Close">
            <vaadin-icon icon="lumo:cross"></vaadin-icon>
          </vaadin-button>
        </vaadin-horizontal-layout>
      </vaadin-notification-card>
    `;
  }
}
```

**TypeScript** — `notification-undo.ts`

```html
<vaadin-notification
  theme="contrast"
  duration="10000"
  position="middle"
  .opened="${this.notificationOpened}"
  @opened-changed="${(e: NotificationOpenedChangedEvent) => {
    this.notificationOpened = e.detail.value;
  }}"
  ${notificationRenderer(this.renderer, [])}
></vaadin-notification>

...

renderer: NotificationLitRenderer = () => html`
  <vaadin-horizontal-layout theme="spacing" style="align-items: center;">
    <div>5 tasks deleted</div>
    <vaadin-button
      theme="tertiary-inline"
      style="margin-left: var(--lumo-space-xl);"
      @click="${this.close}"
    >
      Undo
    </vaadin-button>
    <vaadin-button theme="tertiary-inline" aria-label="Close" @click="${this.close}">
      <vaadin-icon icon="lumo:cross"></vaadin-icon>
    </vaadin-button>
  </vaadin-horizontal-layout>
`;
```

**Java** — `NotificationUndo.java`

```java
Notification notification = new Notification();
notification.setDuration(10000);
notification.addThemeVariants(NotificationVariant.LUMO_CONTRAST);

Div statusText = new Div(new Text("5 tasks deleted"));

Button undoButton = new Button("Undo");
undoButton.addThemeVariants(ButtonVariant.LUMO_TERTIARY_INLINE);
undoButton.getElement().getStyle().set("margin-left",
        "var(--lumo-space-xl)");
undoButton.addClickListener(event -> {
    notification.close();
});

Button closeButton = new Button(new Icon("lumo", "cross"));
closeButton.addThemeVariants(ButtonVariant.LUMO_TERTIARY_INLINE);
closeButton.getElement().setAttribute("aria-label", "Close");
closeButton.addClickListener(event -> {
    notification.close();
});

HorizontalLayout layout = new HorizontalLayout(statusText, undoButton,
        closeButton);
layout.setAlignItems(Alignment.CENTER);

notification.add(layout);
notification.open();
```

Notifications can also contain links to relevant information.

`notification-link-preview.ts`

```typescript
import { html, LitElement } from 'lit';
import '@vaadin/button';
import '@vaadin/horizontal-layout';
import '@vaadin/icon';
import '@vaadin/notification';
import '@vaadin/vaadin-lumo-styles/vaadin-iconset';
import { applyTheme } from 'Frontend/generated/theme';

export class Example extends LitElement {
  protected override createRenderRoot() {
    const root = super.createRenderRoot();
    // Apply custom theme (only supported if your app uses one)
    applyTheme(root);
    return root;
  }

  protected override render() {
    return html`
      <vaadin-notification-card slot="middle">
        <vaadin-horizontal-layout theme="spacing" style="align-items: center;">
          <div>Jason Bailey mentioned you in <a href="#">Project Q4</a></div>
          <vaadin-button theme="tertiary-inline">
            <vaadin-icon icon="lumo:cross"></vaadin-icon>
          </vaadin-button>
        </vaadin-horizontal-layout>
      </vaadin-notification-card>
    `;
  }
}
```

**TypeScript** — `notification-link.ts`

```html
<!-- The duration is set to 0-sec to prevent the notification from auto-close. -->
<vaadin-notification
  duration="0"
  position="middle"
  .opened="${this.notificationOpened}"
  @opened-changed="${(e: NotificationOpenedChangedEvent) => {
    this.notificationOpened = e.detail.value;
  }}"
  ${notificationRenderer(this.renderer, [])}
></vaadin-notification>

...

renderer: NotificationLitRenderer = () => html`
  <vaadin-horizontal-layout theme="spacing" style="align-items: center;">
    <div>Jason Bailey mentioned you in <a href="#">Project Q4</a></div>
    <vaadin-button theme="tertiary-inline" aria-label="Close" @click="${this.close}">
      <vaadin-icon icon="lumo:cross"></vaadin-icon>
    </vaadin-button>
  </vaadin-horizontal-layout>
`;
```

**Java** — `NotificationLink.java`

```java
// When creating a notification using the constructor,
// the duration is 0-sec by default which means that
// the notification does not close automatically.
Notification notification = new Notification();

Div text = new Div(new Text("Jason Bailey mentioned you in "),
        new Anchor("#", "Project Q4"));

Button closeButton = new Button(new Icon("lumo", "cross"));
closeButton.addThemeVariants(ButtonVariant.LUMO_TERTIARY_INLINE);
closeButton.getElement().setAttribute("aria-label", "Close");
closeButton.addClickListener(event -> {
    notification.close();
});

HorizontalLayout layout = new HorizontalLayout(text, closeButton);
layout.setAlignItems(Alignment.CENTER);

notification.add(layout);
notification.open();
```

### <a id="making-interactive-elements-keyboard-accessible"></a>Making Interactive Elements Keyboard-Accessible

Take care to ensure that keyboard-only users can access interactive elements in notifications:

- Make the notification persistent, to prevent it from disappearing before the user has had a chance to interact with it.

- Provide a keyboard shortcut, either to trigger the action itself, or to move focus to the notification card in cases where multiple interactive elements are present.

- Make the shortcut discoverable, for example by displaying it as part of the notification’s content.

`notification-keyboard-a11y-preview.ts`

```typescript
import { html, LitElement } from 'lit';
import '@vaadin/button';
import '@vaadin/horizontal-layout';
import '@vaadin/notification';
import { applyTheme } from 'Frontend/generated/theme';

const isMac = /Macintosh|MacIntel|MacPPC|Mac68K/.test(window.navigator.platform);

export class Example extends LitElement {
  protected override createRenderRoot() {
    const root = super.createRenderRoot();
    // Apply custom theme (only supported if your app uses one)
    applyTheme(root);
    return root;
  }

  protected override render() {
    return html`
      <vaadin-notification-card theme="contrast" slot="middle">
        <vaadin-horizontal-layout style="align-items: center;">
          <div>5 tasks deleted</div>
          <vaadin-button theme="primary" style="margin-left: var(--lumo-space-xl);">
            Undo ${isMac ? '⌘' : 'Ctrl-'}Z
          </vaadin-button>
        </vaadin-horizontal-layout>
      </vaadin-notification-card>
    `;
  }
}
```

**TypeScript** — `notification-keyboard-a11y.ts`

```typescript
protected override render() {
  return html`
    <vaadin-notification
      theme="contrast"
      duration="10000"
      position="middle"
      .opened="${this.notificationOpened}"
      @opened-changed="${(e: NotificationOpenedChangedEvent) => {
        this.notificationOpened = e.detail.value;
      }}"
      ${notificationRenderer(this.renderer, [])}
    ></vaadin-notification>
  `;
}

renderer: NotificationLitRenderer = () => html`
  <vaadin-horizontal-layout style="align-items: center;">
    <div>5 tasks deleted</div>
    <vaadin-button
      style="margin-left: var(--lumo-space-xl);"
      theme="primary"
      @click="${this.close}"
    >
      Undo
      <!-- Ideally, this should be hidden if the
               device does not have a physical keyboard -->
      ${this.isMac ? '⌘' : 'Ctrl-'}Z
    </vaadin-button>
  </vaadin-horizontal-layout>
`;

connectedCallback() {
  super.connectedCallback();

  document.addEventListener('keydown', this.onKeyDown);
}

disconnectedCallback() {
  super.disconnectedCallback();

  document.removeEventListener('keydown', this.onKeyDown);
}

onKeyDown = (event: KeyboardEvent) => {
  if (this.notificationOpened && (event.metaKey || event.ctrlKey) && event.key === 'z') {
    // Handle your custom undo logic here
    // Avoid triggering the native undo action
    event.preventDefault();
    this.close();
  }
};
```

**Java** — `NotificationKeyboardA11y.java`

```java
public Notification show() {
    Notification notification = new Notification();
    notification.setDuration(10000);
    notification.addThemeVariants(NotificationVariant.LUMO_CONTRAST);

    Div statusText = new Div(new Text("5 tasks deleted"));

    Button undoButton = new Button();
    undoButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
    undoButton.getElement().getStyle().set("margin-left",
            "var(--lumo-space-xl)");
    undoButton.getElement().executeJs(
            "const isMac = /Macintosh|MacIntel|MacPPC|Mac68K/.test(window.navigator.platform);"
                    + "this.textContent = `Undo ${isMac ? '⌘' : 'Ctrl-'}Z`;");
    undoButton.addClickListener(event -> {
        notification.close();
    });

    HorizontalLayout layout = new HorizontalLayout(statusText, undoButton);
    layout.setAlignItems(Alignment.CENTER);

    notification.add(layout);
    notification.open();

    return notification;
}

...

public void setupUndoShortcut(Notification notification) {
    Shortcuts.addShortcutListener(notification, notification::close,
            Key.of("z"), KeyModifier.META);
    Shortcuts.addShortcutListener(notification, notification::close,
            Key.of("z"), KeyModifier.CONTROL);
}
```

## <a id="icons-and-other-rich-formatting"></a>Icons and Other Rich Formatting

Icons and other content formatting can be used to provide information and helpful visual cues, for example to make errors and success notifications easier to distinguish for users with color blindness.

`notification-rich-preview.ts`

```typescript
import { html, LitElement } from 'lit';
import { customElement } from 'lit/decorators.js';
import '@vaadin/avatar';
import '@vaadin/button';
import '@vaadin/icon';
import '@vaadin/icons';
import '@vaadin/notification';
import '@vaadin/vaadin-lumo-styles/vaadin-iconset';
import { applyTheme } from 'Frontend/generated/theme';

@customElement('notification-rich-preview')
export class Example extends LitElement {
  protected override createRenderRoot() {
    const root = super.createRenderRoot();
    // Apply custom theme (only supported if your app uses one)
    applyTheme(root);
    return root;
  }

  protected override render() {
    return html`
      <vaadin-notification-card theme="success" slot="middle">
        <vaadin-horizontal-layout theme="spacing" style="align-items: center">
          <vaadin-icon icon="vaadin:check-circle"></vaadin-icon>
          <div>Application submitted!</div>
          <vaadin-button style="margin: 0 0 0 var(--lumo-space-l)">View</vaadin-button>
          <vaadin-button theme="tertiary-inline">
            <vaadin-icon icon="lumo:cross"></vaadin-icon>
          </vaadin-button>
        </vaadin-horizontal-layout>
      </vaadin-notification-card>

      <vaadin-notification-card theme="error" slot="middle">
        <vaadin-horizontal-layout theme="spacing" style="align-items: center">
          <vaadin-icon icon="vaadin:warning"></vaadin-icon>
          <div>Failed to generate report</div>
          <vaadin-button style="margin: 0 0 0 var(--lumo-space-l)">Retry</vaadin-button>
          <vaadin-button theme="tertiary-inline">
            <vaadin-icon icon="lumo:cross"></vaadin-icon>
          </vaadin-button>
        </vaadin-horizontal-layout>
      </vaadin-notification-card>

      <vaadin-notification-card slot="middle">
        <vaadin-horizontal-layout theme="spacing" style="align-items: center">
          <vaadin-avatar name="Jason Bailey"></vaadin-avatar>
          <div><b>Jason Bailey</b> mentioned you in <a href="#">Project Q4</a></div>
          <vaadin-button theme="tertiary-inline">
            <vaadin-icon icon="lumo:cross"></vaadin-icon>
          </vaadin-button>
        </vaadin-horizontal-layout>
      </vaadin-notification-card>

      <vaadin-notification-card slot="middle">
        <vaadin-horizontal-layout theme="spacing" style="align-items: center">
          <vaadin-icon
            icon="vaadin:check-circle"
            style="color: var(--lumo-success-color)"
          ></vaadin-icon>
          <div>
            <b style="color: var(--lumo-success-text-color);">Upload successful</b>
            <div
              style="font-size: var(--lumo-font-size-s); color: var(--lumo-secondary-text-color);"
            >
              <b>Financials.xlsx</b> is now available in <a href="#">Documents</a>
            </div>
          </div>
          <vaadin-button theme="tertiary-inline">
            <vaadin-icon icon="lumo:cross"></vaadin-icon>
          </vaadin-button>
        </vaadin-horizontal-layout>
      </vaadin-notification-card>
    `;
  }
}
```

**TypeScript** — `notification-rich.ts`

```html
<vaadin-notification
  ${notificationRenderer(
    (notification) => html`
      <vaadin-horizontal-layout theme="spacing" style="align-items: center">
        <vaadin-icon icon="vaadin:check-circle"></vaadin-icon>
        <div>Application submitted!</div>
        <vaadin-button
          style="margin: 0 0 0 var(--lumo-space-l)"
          @click="${() => notification.close()}"
        >
          View
        </vaadin-button>
        <vaadin-button
          theme="tertiary-inline"
          @click="${() => notification.close()}"
          aria-label="Close"
        >
          <vaadin-icon icon="lumo:cross"></vaadin-icon>
        </vaadin-button>
      </vaadin-horizontal-layout>
    `,
    []
  )}
  theme="success"
  position="middle"
></vaadin-notification>

<vaadin-notification
  ${notificationRenderer(
    (notification) => html`
      <vaadin-horizontal-layout theme="spacing" style="align-items: center">
        <vaadin-icon icon="vaadin:warning"></vaadin-icon>
        <div>Failed to generate report</div>
        <vaadin-button
          style="margin: 0 0 0 var(--lumo-space-l)"
          @click="${() => notification.close()}"
        >
          Retry
        </vaadin-button>
        <vaadin-button
          theme="tertiary-inline"
          @click="${() => notification.close()}"
          aria-label="Close"
        >
          <vaadin-icon icon="lumo:cross"></vaadin-icon>
        </vaadin-button>
      </vaadin-horizontal-layout>
    `,
    []
  )}
  theme="error"
  position="middle"
></vaadin-notification>

<vaadin-notification
  ${notificationRenderer(
    (notification) => html`
      <vaadin-horizontal-layout theme="spacing" style="align-items: center">
        <vaadin-avatar name="Jason Bailey"></vaadin-avatar>
        <div><b>Jason Bailey</b> mentioned you in <a href="#">Project Q4</a></div>
        <vaadin-button
          theme="tertiary-inline"
          @click="${() => notification.close()}"
          aria-label="Close"
        >
          <vaadin-icon icon="lumo:cross"></vaadin-icon>
        </vaadin-button>
      </vaadin-horizontal-layout>
    `,
    []
  )}
  position="middle"
></vaadin-notification>

<vaadin-notification
  ${notificationRenderer(
    (notification) => html`
      <vaadin-horizontal-layout theme="spacing" style="align-items: center">
        <vaadin-icon
          icon="vaadin:check-circle"
          style="color: var(--lumo-success-color)"
        ></vaadin-icon>
        <div>
          <b style="color: var(--lumo-success-text-color);">Upload successful</b>
          <div
            style="font-size: var(--lumo-font-size-s); color: var(--lumo-secondary-text-color)"
          >
            <b>Financials.xlsx</b> is now available in <a href="#">Documents</a>
          </div>
        </div>
        <vaadin-button
          theme="tertiary-inline"
          @click="${() => notification.close()}"
          aria-label="Close"
        >
          <vaadin-icon icon="lumo:cross"></vaadin-icon>
        </vaadin-button>
      </vaadin-horizontal-layout>
    `,
    []
  )}
  position="middle"
></vaadin-notification>
```

**Java** — `NotificationRich.java`

```java
public static Notification createSubmitSuccess() {
    Notification notification = new Notification();
    notification.addThemeVariants(NotificationVariant.LUMO_SUCCESS);

    Icon icon = VaadinIcon.CHECK_CIRCLE.create();
    Div info = new Div(new Text("Application submitted!"));

    Button viewBtn = new Button("View", clickEvent -> notification.close());
    viewBtn.getStyle().set("margin", "0 0 0 var(--lumo-space-l)");

    HorizontalLayout layout = new HorizontalLayout(icon, info, viewBtn,
            createCloseBtn(notification));
    layout.setAlignItems(FlexComponent.Alignment.CENTER);

    notification.add(layout);

    return notification;
}

public static Notification createReportError() {
    Notification notification = new Notification();
    notification.addThemeVariants(NotificationVariant.LUMO_ERROR);

    Icon icon = VaadinIcon.WARNING.create();
    Div info = new Div(new Text("Failed to generate report!"));

    Button retryBtn = new Button("Retry",
            clickEvent -> notification.close());
    retryBtn.getStyle().set("margin", "0 0 0 var(--lumo-space-l)");

    HorizontalLayout layout = new HorizontalLayout(icon, info, retryBtn,
            createCloseBtn(notification));
    layout.setAlignItems(FlexComponent.Alignment.CENTER);

    notification.add(layout);

    return notification;
}

public static Notification createMentionNotification() {
    Notification notification = new Notification();

    Avatar avatar = new Avatar("Jason Bailey");

    Span name = new Span("Jason Bailey");
    name.getStyle().set("font-weight", "500");

    Div info = new Div(name, new Text(" mentioned you in "),
            new Anchor("#", "Project Q4"));

    HorizontalLayout layout = new HorizontalLayout(avatar, info,
            createCloseBtn(notification));
    layout.setAlignItems(FlexComponent.Alignment.CENTER);

    notification.add(layout);

    return notification;
}

public static Notification createUploadSuccess() {
    Notification notification = new Notification();

    Icon icon = VaadinIcon.CHECK_CIRCLE.create();
    icon.setColor("var(--lumo-success-color)");

    Div uploadSuccessful = new Div(new Text("Upload successful"));
    uploadSuccessful.getStyle().set("font-weight", "600").set("color",
            "var(--lumo-success-text-color)");

    Span fileName = new Span("Financials.xlsx");
    fileName.getStyle().set("font-size", "var(--lumo-font-size-s)")
            .set("font-weight", "600");

    Div info = new Div(uploadSuccessful,
            new Div(fileName, new Text(" is now available in "),
                    new Anchor("#", "Documents")));
    info.getStyle().set("font-size", "var(--lumo-font-size-s)").set("color",
            "var(--lumo-secondary-text-color)");

    HorizontalLayout layout = new HorizontalLayout(icon, info,
            createCloseBtn(notification));
    layout.setAlignItems(FlexComponent.Alignment.CENTER);

    notification.add(layout);

    return notification;
}

public static Button createCloseBtn(Notification notification) {
    Button closeBtn = new Button(VaadinIcon.CLOSE_SMALL.create(),
            clickEvent -> notification.close());
    closeBtn.addThemeVariants(LUMO_TERTIARY_INLINE);

    return closeBtn;
}
```

## <a id="static-helper"></a>Static Helper

For simple, one-off notifications, it’s convenient to use the static `show()` helper method. The helper manages the notification’s lifecycle, and adds and removes it from the DOM automatically.

**TypeScript** — `notification-static-helper.ts`

```typescript
// Show a simple text-based notification
Notification.show('Financial report generated', {
  position: 'middle',
});
// Show a notification with markup using a Lit template
Notification.show(
  html`
    <b>@John:</b>
    &nbsp;
    <span>
      How about lunch at
      <span style="color: var(--lumo-primary-text-color)">12:30pm</span>?
    </span>
  `,
  {
    position: 'middle',
  }
);
```

**Java** — `NotificationStaticHelper.java`

```java
// Show a simple text-based notification
Notification notification = Notification
        .show("Financial report generated");
notification.setPosition(Notification.Position.MIDDLE);
```

## <a id="best-practices"></a>Best Practices

### <a id="use-sparingly"></a>Use Sparingly

Notifications are disruptive by design and should be used sparingly. Use fewer notifications by reserving them for more-important information that might otherwise go unnoticed by the user.

Less-urgent notifications can be provided through a link or drop-down in the application header or footer, instead of via immediate notifications.

**TypeScript** — `notification-popup.ts`

```typescript
protected override render() {
  return html`
    <vaadin-context-menu
      open-on="click"
      ${contextMenuRenderer(
        () => html`<div style="padding: var(--lumo-space-l);">Show notifications here</div>`,
        []
      )}
    >
      <vaadin-button aria-label="notifications" theme="tertiary">
        <vaadin-icon icon="vaadin:bell-o"></vaadin-icon>
        <span theme="badge error primary small pill">4</span>
      </vaadin-button>
    </vaadin-context-menu>
  `;
}
```

**Java** — `NotificationPopup.java`

```java
Span numberOfNotifications = new Span("4");
numberOfNotifications.getElement().getThemeList().addAll(
        Arrays.asList("badge", "error", "primary", "small", "pill"));
numberOfNotifications.getStyle().set("position", "absolute")
        .set("transform", "translate(-40%, -85%)");

Button bellBtn = new Button(VaadinIcon.BELL_O.create());
bellBtn.addThemeVariants(ButtonVariant.LUMO_TERTIARY);
bellBtn.getElement().appendChild(numberOfNotifications.getElement());

Div sampleNotification = new Div(new Text("Show notifications here"));
sampleNotification.getStyle().set("padding", "var(--lumo-space-l)");

ContextMenu menu = new ContextMenu();
menu.setOpenOnClick(true);
menu.setTarget(bellBtn);
menu.add(sampleNotification);
```

### <a id="limit-content-length"></a>Limit Content Length

Aim for one or two lines of content. Notifications should be brief and to the point. More information can be provided through an embedded link or Button.

Do show a preview of longer content, and link to the full details

`notification-content-length-do.ts`

```typescript
import { html, LitElement } from 'lit';
import '@vaadin/button';
import '@vaadin/icon';
import '@vaadin/notification';
import '@vaadin/vaadin-lumo-styles/vaadin-iconset';
import { applyTheme } from 'Frontend/generated/theme';

export class Example extends LitElement {
  protected override createRenderRoot() {
    const root = super.createRenderRoot();
    // Apply custom theme (only supported if your app uses one)
    applyTheme(root);
    return root;
  }

  protected override render() {
    return html`
      <vaadin-notification-card slot="middle">
        <div>
          <div>Aria Bailey</div>
          <div style="font-size: var(--lumo-font-size-s); color: var(--lumo-secondary-text-color);">
            Yeah, I know. But could you help me with...
          </div>
        </div>
        <vaadin-button>View</vaadin-button>
        <vaadin-button theme="tertiary-inline">
          <vaadin-icon icon="lumo:cross"></vaadin-icon>
        </vaadin-button>
      </vaadin-notification-card>
    `;
  }
}
```

Don’t display all details in the notification

`notification-content-length-dont.ts`

```typescript
import { html, LitElement } from 'lit';
import '@vaadin/button';
import '@vaadin/icon';
import '@vaadin/notification';
import '@vaadin/vaadin-lumo-styles/vaadin-iconset';
import { applyTheme } from 'Frontend/generated/theme';

export class Example extends LitElement {
  protected override createRenderRoot() {
    const root = super.createRenderRoot();
    // Apply custom theme (only supported if your app uses one)
    applyTheme(root);
    return root;
  }

  protected override render() {
    return html`
      <vaadin-notification-card slot="middle">
        <div>
          <div>New message from Aria Bailey</div>
          <div style="font-size: var(--lumo-font-size-s); color: var(--lumo-secondary-text-color);">
            Yeah, I know. But could you help me with this. I’m not sure where the bug is in my CSS?
            The checkmark doesn’t get the right color. I’m trying to use the CSS custom properties
            from our design system, but for some reason it’s not working.
          </div>
        </div>
        <vaadin-button theme="tertiary-inline">
          <vaadin-icon icon="lumo:cross"></vaadin-icon>
        </vaadin-button>
      </vaadin-notification-card>
    `;
  }
}
```

## <a id="related-components"></a>Related Components

| Component                                                  | Usage recommendations                                                                           |
| ---------------------------------------------------------- | ----------------------------------------------------------------------------------------------- |
| [Dialog](https://vaadin.com/docs/v23/components/dialog.md) | Dialog should be used instead of Notification for anything that requires immediate user action. |

`77E15AD0-F634-4D81-8C4D-FAC7A21D889B`
