ハウツー コンポーネント – ハウツー ツールチップ

まとめ

<howto-tooltip> は、要素がキーボード フォーカスを受け取ったとき、またはマウスがその要素にカーソルを合わせたときに、その要素に関連する情報を表示するポップアップです。ツールチップをトリガーする要素は、aria-describedby でツールチップ要素を参照します。

この要素はロール tooltip を自己適用し、ツールチップ自体にフォーカスすることはできないため、tabindex を -1 に設定します。

リファレンス

デモ

GitHub でライブデモを見る

使用例

<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>

コード

class HowtoTooltip extends HTMLElement {

コンストラクタは、1 回だけ実行する必要がある処理を行います。

  constructor() {
    super();

これらの関数はさまざまな場所で使用されるため、常に正しいこの参照をバインドする必要があるため、1 回実行してください。

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

connectedCallback() は、要素が DOM に挿入されると起動されます。初期ロール、tabindex、内部状態、インストール イベント リスナーを設定するのに適しています。

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

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

    this._hide();

ツールチップをトリガーする要素は、aria-describedby でツールチップ要素を参照します。

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

ツールチップは、ターゲットからのフォーカス イベントまたはぼかしイベント、およびターゲットでのマウスオーバー イベントをリッスンする必要があります。

    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() は、connectedCallback() で設定されたイベント リスナーの登録を解除します。

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

表示するツールチップがない場合でもトリガーされないように、既存のリスナーを削除します。

    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);