I'm trying to implement a tooltip, like GitHub avatar hover. When an avatar is mouseover (hover), a tooltip is presented over the avatar. For this, I'm using popper.js.
<!-- I'm using avatar to act as the container. -->
<!-- classes are omitted for simplicity. -->
<div id="avatar"">
<span>DM</span>
<!-- Hidden tooltip -->
<div id="tooltip" class="hidden">
<p>Show me when hovered</p>
</div>
</div>
JavaScript:
import { createPopper } from '@popperjs/core';
// Event function for mouseover when avatar is mouseovered
showTooltip = (e) => {
let tooltip = document.getElementById('tooltip');
let avatar = document.getElementById('avatar');
tooltip.classList.remove('hidden')
// Use popper to position the tooltip over the avatar
createPopper(avatar, tooltip)
}
This works as expected. When I move the cursor over the tooltip, the tooltip is removed:
let avatar = document.getElementById('avatar');
let tooltip = document.getElementById('tooltip');
avatar.addEventListener('mouseout', (e) => {
if (!avatar.contains(e.target)) {
// Hide tooltip
tooltip.classList.add('hidden')
}
})
The above would be ideal if I move my cursor left/right/bottom, away from the avatar. When I move the cursor up, into the tooltip container, the tooltip closes. I'm going "overkill" now:
[..]
// yarn add debounce
import debounce from 'debounce';
[..]
avatar.addEventListener('mouseout', debounce(function(e) {
if (!avatar.contains(e.target)) {
// Hide tooltip
tooltip.classList.add('hidden')
}
}, 300));
My code looks messy as it is. How to achieve a Github-like tooltip, with "vanilla" JavaScript?