Komponenty z instrukcjami – etykietka z instrukcjami

Podsumowanie

<howto-tooltip> to wyskakujące okienko, które wyświetla informacje związane z elementem, gdy ten zostanie zaznaczony za pomocą klawiatury lub gdy najedziesz na niego kursorem myszy. Element, który powoduje wyświetlenie etykiety, odwołuje się do elementu etykiety za pomocą atrybutu aria-describedby.

Element samodzielnie stosuje rolę tooltip i ustawia wartość tabindex na -1, ponieważ samo okienko tooltip nigdy nie może być fokusowane.

Dokumentacja

Prezentacja

Wyświetl demonstrację na żywo w GitHubie

Przykład użycia

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

Kod

class HowtoTooltip extends HTMLElement {

Konstruktor wykonuje zadanie, które musi zostać wykonane dokładnie raz.

  constructor() {
    super();

Te funkcje są używane w wielu miejscach i zawsze muszą wiązać prawidłowe odwołanie, więc zrób to raz.

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

connectedCallback() jest wywoływany, gdy element jest wstawiany do DOM. Jest to dobre miejsce na ustawienie początkowej roli, tabindex, stanu wewnętrznego i detektorów zdarzeń.

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

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

    this._hide();

Element, który powoduje wyświetlenie etykiety, odwołuje się do elementu etykiety za pomocą aria-describedby.

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

Opis musi nasłuchiwać zdarzeń focus/blur z celu, a także zdarzeń hover nad celem.

    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() powoduje odrejestrowanie detektorów zdarzeń skonfigurowanych w connectedCallback().

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

Usuń dotychczasowych słuchaczy, aby nie uruchamiali się, nawet jeśli nie ma żadnej etykiety.

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