DEV Community

Discussion on: Web components with vanilla JavaScript

Collapse
 
dannyengelman profile image
Danny Engelman

I was too soon with my <span> remark; missed that you added a second span; can't you work that in you base HTML somehow?

Thread Thread
 
dannyengelman profile image
Danny Engelman • Edited

That double span didn't leave my mind today..

I would write it like this: jsfiddle.net/CustomElementsExample...

<my-tooltip tip-text="World!">Hello</my-tooltip>
<script>
  customElements.define("my-tooltip", class Tooltip extends HTMLElement {
    constructor() {
      super()
        .attachShadow({mode: "open"})
        .innerHTML = /*html*/ `
            <style>
             :host{ font-size: 24px; display: inline-block }
             span:not(:empty) {
                   padding: 1rem;
                   border-radius: 10px;
                   background-color: black;
                   color: white;
               }
            </style>
            <slot></slot> πŸ‘‰ <span></span>`;
      const tooltip = this.shadowRoot.querySelector("span");
      this.onmouseover = (evt) => {
        tooltip.innerHTML = this.getAttribute("tip-text") || "Default Text";
      }
      this.onmouseleave = (evt) => {
        tooltip.innerHTML = "";
      }
    }
  })
</script>
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
leeoc profile image
Lee O'Connell

Love this! Never thought a web component could be so clean. Haven’t seen the :not() css operator before, thanks for your comments, definitely have picked up a few new ideas and things to learn 😊