Add dynamic event listeners in LWC

Let's look at how to add event listeners dynamically in LWC templates.

This is something you would need rarely but definitely worth knowing something like this is possible.

Let's look at how to add event listeners dynamically in LWC templates.

If the event is always a click event, then we can straight away use onclick attribute on the template tags (we don't have to take this route).

In the renderedCallback life cycle hook am trying to use the native JavaScript syntax to add the event listeners.

import { LightningElement } from "lwc";

export default class ExploreEventsBubbling extends LightningElement {

renderedCallback() {

        //get reference to "p" tag and add event listeners
        //I can also use change, mouseover and other events
    this.template
      .querySelector("p")
      .addEventListener("click", (e) => console.log("NATIVE JS P"), false);
      
    //get reference to "span" tag and add event listeners  
    this.template
      .querySelector("span")
      .addEventListener("click", (e) => console.log("NATIVE JS SPAN"), false);
      
    //get reference to "div" tag and add event listeners  
    this.template
      .querySelector("div")
      .addEventListener("click", (e) => console.log("NATIVE JS DIV"), false);
}

handleClick() {
    console.log('BUTTON IS CLICKED!!!');                                 
}
exploreEventsBubbling.js

Here is the template file associated to the web component.

<template>
  <div>
    <span>
      <p>
        <lightning-button
          label="Click Me"
          onclick={handleClick}
        ></lightning-button>
      </p>
    </span>
  </div>
</template>
exploreEventsBubbling.html

Hope this helps!