Back to Lit

04

packages/lit-dev-content/site/tutorials/content/tooltip/04.md

latest1.8 KB
Original Source

The tooltip should be shown near the target element. To allow some control over this, first create an offset property inside the class definition:

{% switchable-sample %}

ts
// Position offset
@property({type: Number})
offset = 4;
js
static properties = {
  offset: {type: Number},
};

constructor() {
  super();
  // Position offset
  this.offset = 4;
}

{% endswitchable-sample %}

Since the target element's position may change, position the tooltip each time it's shown. Again, to do this simply and robustly, use inline styling.

{% switchable-sample %}

ts
show = () => {
  this.style.cssText = '';
  // Position the tooltip near the target.
  const {x, y, height} = this.target!.getBoundingClientRect();
  this.style.left = `${x}px`;
  this.style.top = `${y + height + this.offset}px`;
};
js
show = () => {
  this.style.cssText = '';
  // Position the tooltip near the target.
  const {x, y, height} = this.target.getBoundingClientRect();
  this.style.left = `${x}px`;
  this.style.top = `${y + height + this.offset}px`;
};

{% endswitchable-sample %}

{% aside "info" %}

The getBoundingClientRect API provides layout metrics for the target element.

The object destructuring syntax is used on its return value.

{% endaside %}

After adding the code, try triggering the tooltips. The tooltips for the input and greeting should be better aligned, showing below the target elements. However, the tooltip for box 3 isn't sized correctly and depending on your screen size, the tooltips for the boxes may run off the bottom of the preview window. You'll fix that next.