Is there any way to make setter more reusable in Web Components

Viewed 69

Here is my code:

class Tooltip extends HTMLElement {
  constructor() {
    super()
    this.attachShadow({mode: 'open'})
  }

  set position(boundingClientRect) {
    this.style.setProperty('--position', checksth(boundingClientRect));
    this.style.setProperty('--left', "0px")
    this.style.setProperty('--right', "0px")
    this.style.setProperty('--bottom', boundingClientRect.y + 100 + "px" )
  }

  // render HTML
  ...
}

customElements.define('x-tooltip', Tooltip)

and then I'am calling it on other js file

const tooltip = document.createElement('x-tooltip')
tooltip.position = document.querySelector('.hover-over').getBoundingClientRect()
document.body.appendChild(tooltip)

The problem is I have an other tooltip that pretty similar to Tooltip component except the position style (might be shown at the top right concer, top left corner, bottom left corner...). One possible solution is to create a new Class like TopLeftTooltip, TopRightTooltip that extends Tooltip override the setter, but I don't want to create multiple component, is that any more clever solution?

1 Answers

Similar to building a house; put on your architect hat before you start piling bricks.

Design your HTML element and attributes before you dive into JS code:

<x-tooltip><x-tooltip>

<x-tooltip position="topleft"><x-tooltip>

<x-tooltip position="bottomright"><x-tooltip>

Then make it work with JS code.

The architect in me would not pass a position, instead pass the element the tooltip is a tooltip for. Keep the position logic inside the tooltip.

Related