Podsumowanie
<howto-tooltip>
to wyskakujące okienko, które wyświetla informacje związane z elementem, gdy zaznaczono go na klawiaturze lub najechano na niego kursorem myszy.
Element, który wywołuje etykietkę, odwołuje się do elementu etykietki z atrybutem aria-describedby
.
Element samodzielnie stosuje rolę tooltip
i ustawia tabindex
na wartość -1, ponieważ sam etykietka nigdy nie może zostać zaznaczona.
Dokumentacja
Wersja demonstracyjna
Zobacz prezentację 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 działanie, które trzeba wykonać dokładnie raz.
constructor() {
super();
Te funkcje są używane w kilku miejscach i zawsze trzeba powiązać właściwe odwołanie.
this._show = this._show.bind(this);
this._hide = this._hide.bind(this);
}
connectedCallback()
uruchamia się, gdy element zostanie wstawiony do modelu DOM. Jest to dobre miejsce do skonfigurowania roli początkowej, indeksu tabulacji, stanu wewnętrznego oraz instalowania 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 wywołuje etykietkę, odwołuje się do elementu etykietki z atrybutem aria-describedby
.
this._target = document.querySelector('[aria-describedby=' + this.id + ']');
if (!this._target)
return;
Etykietka musi wychwytywać zdarzenia skupienia/rozmycia z celu oraz zdarzenia najechania kursorem na ten cel.
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()
wyrejestrowuje detektory zdarzeń skonfigurowane w zadaniu connectedCallback()
.
disconnectedCallback() {
if (!this._target)
return;
Usuń istniejące detektory, aby nie uruchamiały się, mimo że nie ma etykietki do wyświetlenia.
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);