I'm showing a tooltip when you hover an element with the tooltip
attribute. E.g. <div class="example" tooltip="Hello World">Hover me.</div>
I also have to set the position of the tooltip based on its width, and because I use width: max-content
for the element, I have to do something like shown in the code example.
Is there any way I can make my code more efficient? I feel like I'm making it unnecessarily complicated.
(function() {
var tooltip = document.querySelectorAll("[tooltip]");
callback = (element, index, array) => {
tooltip[index].onmouseenter = () => {
let data = element.getAttribute("tooltip");
let child = document.createElement("div");
child.className = "tooltip";
child.innerHTML = data;
element.appendChild(child);
child.style.left = "50%";
child.style.marginLeft = - (child.offsetWidth / 2) + "px";
}
tooltip[index].onmouseleave = () => {
if(element.getElementsByClassName("tooltip")[0] != undefined) {
element.removeChild(element.getElementsByClassName("tooltip")[0]);
}
}
}
tooltip.forEach(callback);
})();
/* Don't review this CSS; it was added just for the demo. */
div[tooltip] { width: max-content; margin: auto; }
<div class="example" tooltip="Hello World">Hover me.</div>