Skip to content

Instantly share code, notes, and snippets.

@vincentnavetat
Last active January 15, 2021 09:41
Show Gist options
  • Save vincentnavetat/77f2045e6286253a84c1049596cd3a3c to your computer and use it in GitHub Desktop.
Save vincentnavetat/77f2045e6286253a84c1049596cd3a3c to your computer and use it in GitHub Desktop.
Tooltip web component JS
class Tooltip extends HTMLElement {
connectedCallback() {
this.setup();
}
toggle() {
if (this.classList.contains('tooltip--open')) {
this.close();
} else {
this.open();
}
}
open() {
this.classList.add('tooltip--open');
this.handleDropdownPosition();
}
close() {
this.classList.remove('tooltip--open');
}
setup() {
this.placeholder = this.querySelector('[data-tooltip-placeholder]');
this.dropdown = this.querySelector('[data-tooltip-dropdown]');
this.placeholder.addEventListener('mouseover', () => this.handleDropdownPosition());
this.placeholder.addEventListener('touchstart', () => this.toggle());
}
}
function dismissAllTooltips(event) {
if (typeof event.target.closest !== 'function') return;
const currentTooltip = event.target.closest('wow-tooltip');
document.querySelectorAll('.tooltip--open').forEach(tooltip => {
if (tooltip === currentTooltip) return;
tooltip.classList.remove('tooltip--open');
});
}
customElements.define('wow-tooltip', Tooltip);
document.addEventListener('touchstart', e => dismissAllTooltips(e));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment