Last active
January 15, 2021 09:41
-
-
Save vincentnavetat/77f2045e6286253a84c1049596cd3a3c to your computer and use it in GitHub Desktop.
Tooltip web component JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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