javascriptpolymerweb-componentpolymer-3.xlit-element

Mouse-Over event Lit-Element/Polymer


Is there a way to create a custom event in in Lit-Element/Polymer, such as a mouse-over event? I've been searching for this a while now, but I can seem to find a way of doing it. I know about events in Lit-Element, like @click, but nothing about mouse-over events.


Solution

  • This can be done using lit-html @event bindings.

    For the mouseover event type, use @mouseover="${this.handleMouseover}"

    For more information on lit-element event listeners, see https://lit-element.polymer-project.org/guide/events

    Live example:

    <script src="https://unpkg.com/@webcomponents/webcomponentsjs@latest/webcomponents-loader.js"></script>
    <script type="module">
      import { LitElement, html, css } from 'https://unpkg.com/lit-element/lit-element.js?module';
      
      class MyElement extends LitElement {
        static get styles() {
          return [
            css`
              span {
                padding: 4px 8px;
                border: 2px solid orange;
              }
            `
          ];
        }
        
        render() {
          return html`
            <span
              @mouseover="${this.handleEvent}"
              @mouseleave="${this.handleEvent}">
              Hover me
            </span>
          `;
        }
        
        handleEvent(e) {
          console.log(`Event type: ${e.type}`);
        }
      }
      customElements.define('my-element', MyElement);
    </script>
    <my-element></my-element>