Search code examples
javascriptlit-html

How do I add and remove classes using event listeners in Lit-HTML?


I would like to add and remove 'over' from my class on an element created using a lit-html template triggered by 'dragEnter' and 'dragLeave':

#app {
  background-color: #72a2bc;
  border: 8px dashed transparent;
  transition: background-color 0.2s, border-color 0.2s;
}

#app.over {
  background-color: #a2cee0;
  border-color: #72a2bc;
}
const filesTemplate = () =>
html`
  <button id="app"     
    @dragover=${??}
    @dragleave=${??}     
  >
    Click Me
  </button>
`;

In my old system I called these methods in a separate module via an event emitter, but I am hoping I can make it all defined in the template using lit-html.

 dragEnter(e) {
    this.view.element.className += ' over';
  }

  dragLeave(e) {
    this.view.element.className = element.className.replace(' over', '');
  }


Solution

  • It depends what your custom element looks like. With your template you could just put @dragover=${this.dragEnter}. However, if you want this to apply to your entire custom element and not just the button you can do something like this:

    connectedCallback() {
    super.connectedCallback();
    
    this.addEventListener('dragover', this.dragEnter);
    
    }
    

    If you do not have custom element and just use lit-html by itself you have to put your event handlers dragEnter(e)and dragLeave(e) into the template like so: @dragover=${this.dragEnter}

    You need to add the class with classList.add in dragEnter and remove it in dragLeave. In the future you maybe can use classMap directive in lit-html, however there is nothing wrong with just using classList. I would stick with just using classList. In a very distant future css might also have a selector for it: Is there a CSS ":drop-hover" pseudo-class?