Componentes de instruções – dica de ferramenta

Resumo

Um <howto-tooltip> é um pop-up que mostra informações relacionadas a um elemento quando ele recebe o foco do teclado ou o mouse passa sobre ele. O elemento que aciona a dica faz referência a ele com aria-describedby.

O elemento aplica automaticamente o papel tooltip e define tabindex como -1, já que a dica nunca pode ser focada.

Referência

Demonstração

Confira a demonstração ao vivo no GitHub

Exemplo de uso

<div class="text">
<label for="name">Your name:</label>
<input id="name" aria-describedby="tp1"/>
<howto-tooltip id="tp1">Ideally your name is Batman</howto-tooltip>
<br>
<label for="cheese">Favourite type of cheese: </label>
<input id="cheese" aria-describedby="tp2"/>
<howto-tooltip id="tp2">Help I am trapped inside a tooltip message</howto-tooltip>

Código

class HowtoTooltip extends HTMLElement {

O construtor faz um trabalho que precisa ser executado exatamente uma vez.

  constructor() {
    super();

Essas funções são usadas em vários lugares e sempre precisam vincular a referência correta, portanto, faça isso uma vez.

    this._show = this._show.bind(this);
    this._hide = this._hide.bind(this);
}

connectedCallback() é disparado quando o elemento é inserido no DOM. É recomendável definir o papel inicial, o tabindex, o estado interno e os listeners de eventos de instalação.

  connectedCallback() {
    if (!this.hasAttribute('role'))
      this.setAttribute('role', 'tooltip');

    if (!this.hasAttribute('tabindex'))
      this.setAttribute('tabindex', -1);

    this._hide();

O elemento que aciona a dica faz referência ao elemento com aria-describedby.

    this._target = document.querySelector('[aria-describedby=' + this.id + ']');
    if (!this._target)
      return;

A dica precisa detectar eventos de foco/desfoque do alvo, bem como eventos de passar o cursor sobre ele.

    this._target.addEventListener('focus', this._show);
    this._target.addEventListener('blur', this._hide);
    this._target.addEventListener('mouseenter', this._show);
    this._target.addEventListener('mouseleave', this._hide);
  }

disconnectedCallback() cancela o registro dos listeners de eventos que foram configurados em connectedCallback().

  disconnectedCallback() {
    if (!this._target)
      return;

Remova os listeners atuais para que não sejam acionados mesmo que não haja uma dica para mostrar.

    this._target.removeEventListener('focus', this._show);
    this._target.removeEventListener('blur', this._hide);
    this._target.removeEventListener('mouseenter', this._show);
    this._target.removeEventListener('mouseleave', this._hide);
    this._target = null;
  }

  _show() {
    this.hidden = false;
  }

  _hide() {
    this.hidden = true;
  }
}

customElements.define('howto-tooltip', HowtoTooltip);