typescriptlit

How to handle mousedown in lit


I have the a list of thumbnails that are rendered to the screen as follows:

  <div
         class="color"
         style="background:${rgbToHex(color.value.r, color.value.g, color.value.b )}"
  >
      <context-menu></context-menu>
  </div>

When I hold on the color div, I want to show the context menu. Only on hold not hover. How can I do that using lit and typescript? Please note its more than one thumbnail that's rendered. So I need to show the context menu for the thumbnail that the person holds on.


Solution

  • You can show the menu on mousedown event and hide it on either mouseup or mouseleave.

    Lit has syntax for declaratively adding event listeners so you can do something like the following assuming you have methods on your element class to handle showing/hiding the menu.

    html`
      <div
        @mousedown=${this.showMenu}
        @mouseup=${this.hideMenu}
        @mouseleave=${this.hideMenu}
        class="color"
        style="background:${rgbToHex(color.value.r, color.value.g, color.value.b )}"
      >
          <context-menu></context-menu>
      </div>`;