Struggling to complete a task on Javascript.info involving an "a" tag. The objective is simple - place (and remove) a tooltip above the element upon hover. No issues with positioning over the roof or house, but as soon as I try to place the box above the link, it breaks and seems unsolvable.
Asking for assistance here since the solution provided uses position:fixed while attempting to use position:absolute instead. Merely copying the solution doesn't contribute to learning. The trouble arises on line 77 and 78, specifically while assigning tooltip.style.left and tooltip.style.top.
If assigned with a literal value (e.g., "-58px"), it works as expected. Anything else reverts to the default of the tooltip on "house." Tried debugging with tactical alerts, only ended up confused. It appears using a computed value causes defaults, whereas a literal functions correctly.
Seeking an explanation for this behavior along with insights (correction on understanding position:absolute, element size properties, or similar).
The script code below modified from line 64 onwards (rest credits to original authors):
<!DOCTYPE HTML>
<html>
<head>
...
// Script Code Modified Here
house.onmouseover= function(event){
let target= event.target.closest('[data-tooltip]');
let tooltip= document.createElement('div');
tooltip.textContent= target.dataset.tooltip;
tooltip.classList.add("tooltip");
target.append(tooltip);
if(!tooltip.parentElement.style.position){
tooltip.parentElement.style.position= 'relative';
}
tooltip.style.position= 'absolute';
tooltip.style.top= "-"+(tooltip.offsetHeight+5)+"px";
tooltip.style.left= -target.clientLeft+(target.offsetWidth-tooltip.offsetWidth)/2+"px";
//alert("-"+(tooltip.offsetHeight+5)+"px");
//alert(tooltip.style.top);
}
house.onmouseout= function(event){
let target= event.target.closest('[data-tooltip]');
tooltips= target.querySelectorAll('.tooltip');
for(tooltip of tooltips){
tooltip.remove();
}
}
</script>
<body>
...
</body>
</html>
Appreciate any help! :)