How to handle mousedown in lit

54 views Asked by At

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.

2

There are 2 answers

0
Augustine Kim On BEST ANSWER

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>`;
0
Danny '365CSI' Engelman On

This is a non-Lit version

<script>
  customElements.define('hover-stationary', class extends HTMLElement {
    constructor() {
      const createElement = (tag, props = {}) => Object.assign(document.createElement(tag), props);
      let timeoutId;
      super().attachShadow({ mode: "open" }).append(
        createElement("style", { innerHTML: `:host { display: inline-block }` }),
        createElement("slot", {}),
      );
      this.onmouseenter = (e) => {
        timeoutId = setTimeout(() => this.show(), 2000);
      }
      this.onmouseleave = (e) => {
        this.hide();
        clearTimeout(timeoutId);
      }
    }
    show(){ this.style.background = "green"   }
    hide(){ this.style.background = "initial" }
  });
</script>
<hover-stationary title="Hover over me for 2 seconds">Hover target #1</hover-stationary>
<hover-stationary title="Hover over me for 2 seconds">Hover target #2</hover-stationary>