Resumen
Un <howto-tooltip>
es una ventana emergente que muestra información relacionada con un elemento cuando este recibe el enfoque del teclado o el mouse se coloca sobre él.
El elemento que activa la información sobre la herramienta hace referencia a este elemento con aria-describedby
.
El elemento aplica de forma automática la función tooltip
y establece tabindex
en -1, ya que la información sobre la herramienta nunca se puede enfocar.
Reference
- Instructivo: Componentes en GitHub
- Patrón de información sobre la herramienta en prácticas de creación de ARIA 1.1
Demostración
Ver la demostración en vivo en GitHub
Ejemplo 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>
Escribe código
class HowtoTooltip extends HTMLElement {
El constructor realiza tareas que se deben ejecutar exactamente una vez.
constructor() {
super();
Estas funciones se usan en varios lugares y siempre debes vincular la referencia correcta. Hazlo una vez.
this._show = this._show.bind(this);
this._hide = this._hide.bind(this);
}
connectedCallback()
se activa cuando el elemento se inserta en el DOM. Es un buen lugar para establecer el rol inicial, tabindex, estado interno e instalar objetos de escucha de eventos.
connectedCallback() {
if (!this.hasAttribute('role'))
this.setAttribute('role', 'tooltip');
if (!this.hasAttribute('tabindex'))
this.setAttribute('tabindex', -1);
this._hide();
El elemento que activa la información sobre la herramienta hace referencia a este elemento con aria-describedby
.
this._target = document.querySelector('[aria-describedby=' + this.id + ']');
if (!this._target)
return;
La información sobre la herramienta debe escuchar los eventos de enfoque/desenfoque del objetivo, así como los eventos de colocar el cursor sobre el objetivo.
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 el registro de los objetos de escucha de eventos que se configuraron en connectedCallback()
.
disconnectedCallback() {
if (!this._target)
return;
Quita los objetos de escucha existentes para que no se activen aunque no haya información sobre la herramienta 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);