HowTo कॉम्पोनेंट – कैसे करें-टूलटिप

ईवा गैस्परोविच

खास जानकारी

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

ये फ़ंक्शन कई जगहों पर इस्तेमाल किए जाते हैं और हमेशा सही रेफ़रंस को बाइंड करने की ज़रूरत होती है. इसलिए, ऐसा एक बार ही करें.

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

जब एलिमेंट को डीओएम में डाला जाता है, तब connectedCallback() ट्रिगर होता है. शुरुआती भूमिका, tabindex, आंतरिक स्थिति, और इवेंट लिसनर को इंस्टॉल करने के लिए यह एक अच्छी जगह है.

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