סיכום
<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 {
ה-constructor פועל שיש לבצע אותו בדיוק פעם אחת.
constructor() {
super();
הפונקציות האלה משמשות במספר מקומות, ותמיד צריך לקשר את ההפניה הנכונה. יש לבצע זאת פעם אחת.
this._show = this._show.bind(this);
this._hide = this._hide.bind(this);
}
connectedCallback()
מופעל כשהאלמנט מוכנס ל-DOM. מומלץ להגדיר את התפקיד הראשוני, הכרטיסייה אינדקס, המצב הפנימי ולהתקין פונקציות event listener.
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()
מבטל את הרישום של פונקציות event listener שהוגדרו ב-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);