DEV Community

Discussion on: Building Web Components with Vanilla JavaScript

Collapse
 
nickytonline profile image
Nick Taylor • Edited

I did a hello world in web components a couple of years ago, but haven't touched them since. Thanks for the refresher!

I'd just make one suggestion about adding event listeners. This is not web component specific, but for adding event listeners in general. In the case of the rainbow-text component, the number of <span />s increases for every additional letter in the text attribute, so the number of event listeners per instance of the component is n letters * 2 (mouse over + animation end events).

You can end up with a lot of events very quickly just for one instance of the component. What you can do is add an event listener for each event type on the parent <div /> you create in aspittel/rainbow-word-webcomponent and then the power of event bubbling is your friend.

e.g.

class RainbowText extends HTMLElement {
  …

  addEventListeners(div) {
    div.addEventListener("mouseover", e => {
      const { target } = e;

      if (target.tagName === "SPAN") {
        target.classList.add("hovered");
        console.log(`mousing over ${target.tagName}`);
      }
    });

    div.addEventListener("animationend", e => {
      const { target } = e;

      if (target.tagName === "SPAN") {
        target.classList.remove("hovered");
        console.log(`mousing over ${target.tagName}`);
      }
    });
  }

  …

  render() {
    const div = document.createElement("div");
    div.classList.add("header");
    this.addEventListeners(div);
    this.shadowRoot.appendChild(div);
    this.addSpans(div);
    this.addStyle();
  }
}
Collapse
 
aspittel profile image
Ali Spittel

Ah thank you for spotting that!