HowTo Components – howto-tooltip

خلاصه

<howto-tooltip> یک پنجره بازشو است که اطلاعات مربوط به یک عنصر را هنگامی که عنصر فوکوس صفحه کلید را دریافت می کند یا ماوس روی آن قرار می گیرد، نمایش می دهد. عنصری که راهنمای tooltip را فعال می کند به عنصر 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() {
    super();

این توابع در بسیاری از مکان‌ها استفاده می‌شوند، و همیشه باید این مرجع را به درستی متصل کنید، بنابراین یک بار این کار را انجام دهید.

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

عنصری که راهنمای tooltip را فعال می کند به عنصر tooltip با 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);