Ian Guimarães
Ian Guimarães

Reputation: 421

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.

Upvotes: 2

Views: 4859

Answers (2)

SebHex
SebHex

Reputation: 66

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>

Upvotes: 5

Ian Guimar&#227;es
Ian Guimar&#227;es

Reputation: 421

So I just figured it out, and just going to post here if anyone has the same difficulty.

You have to use CustomEvents, here some code example:

in your element's firstUpdate method you should add a new EventListener

firstUpdated(){
    this.addEventListener('mouseover', this.mouseOverHandler);
}

and declare the method

   mouseOverHandler(){
       console.log('Hello');
}

Simple as that!!!

Upvotes: 1

Related Questions