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()는 요소가 DOM에 삽입될 때 실행됩니다. 초기 역할, 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);