Vaadin Elements - Context Menu - Targeting the Menu

Targeting the Menu

The vaadin-context-menu element needs to process an event to open the menu overlay. There are multiple ways of achieving this behavior, they are described below.

Wrapping the Page Content

By default, the vaadin-context-menu element itself listens for the event opening the menu. In order to have a context menu on your content, wrap your page content with the vaadin-context-menu element and add a template element with a menu. Example:

<vaadin-context-menu>
  <template>
    <paper-menu>
      <paper-item>First menu item</paper-item>
      <paper-item>Second menu item</paper-item>
    </paper-menu>
  </template>

  <p>This paragraph has the context menu provided in the above template.</p>
  <p>Another paragraph with the context menu.</p>
</vaadin-context-menu>
vaadin context menu on content
Figure 1. vaadin-context-menu targeted on the text paragraphs

Without Wrapping

In case if you do not want to wrap the page content, you can listen for events on an element outside the vaadin-context-menu by setting the listenOn property:

<vaadin-context-menu id="customListener">
  <template>
    <paper-menu>
      ...
    </paper-menu>
  </template>
</vaadin-context-menu>

<div id="menuListener">The element that listens for the context menu.</div>

<script>
  var contextMenu = document.querySelector('vaadin-context-menu#customListener');
  contextMenu.listenOn = document.querySelector('#menuListener');
</script>

Filtering Menu Targets

By default, the listener element and all its descendants open the context menu. You can filter the menu targets to a desired set of elements inside the listener element by setting the selector property.

In the following example, only the elements matching .has-menu will have the context menu:

<vaadin-context-menu selector=".has-menu">
  <template>
    <paper-menu>
      ...
    </paper-menu>
  </template>

  <p class="has-menu">This paragraph opens the context menu</p>
  <p>This paragraph does not open the context menu</p>
</vaadin-context-menu>

Opening Using JavaScript

If the declarative menu targeting, which was described above, is not applicable, you can open the menu manually by calling the open method of the vaadin-context-menu:

<script>
  target.addEventListener('vaadin-contextmenu', function(event) {
    document.querySelector('vaadin-context-menu#myMenu').open(event);
  });
</script>

See the Opening and Closing page for more information about the open method.