Reputation: 4617
Hi guys i have following code which is i am using to create a simple tooltip.
html
<div class="x">
<div class="abc">abc</div>
</div>
javascript
//Finding the elements position
var elmPosition = function (elm) {
var x = 0,
y = 0;
while (elm) {
x += (elm.offsetLeft - elm.scrollLeft + elm.clientLeft);
y += (elm.offsetTop - elm.scrollTop + elm.clientTop);
elm = elm.offsetParent;
}
return {
x: x,
y: y
};
};
//Creating and adding the tooltip to document
document.querySelector('.abc').addEventListener("mouseover", function () {
var elm = document.createElement("div");
var position = elmPosition(document.querySelector('.abc'));
elm.textContent = 'just a tooltip';
elm.classList.add('tooltip');
document.body.appendChild(elm);
elm.style.position = 'absolute';
elm.style.top = (position.y - 20) + 'px';
});
//remove tooltip on mouse out
document.querySelector('.abc').addEventListener("mouseout", function () {
document.body.removeChild(document.body.querySelector('.tooltip'));
})
The generated tooltip should always stay top of the mouse hovered element. This code perfectly works until the page is scrolled. When then page is scrolled the position of the tooltip is pushed to very far from the mouse hovered element. Could someone please help me to find out what the issue is. Thanks :)
Upvotes: 1
Views: 234
Reputation: 1619
What you're checking for using scrollLeft
is how far elm
is scrolled. What you want is how far the window is scrolled I'm guessing.
Use window.pageYOffset
and window.pageXOffset
like so:
while (elm) {
x += (elm.offsetLeft - window.pageXOffset + elm.clientLeft);
y += (elm.offsetTop - window.pageYOffset + elm.clientTop);
elm = elm.offsetParent;
}
EDIT
After trying it out it doesn't make much sense involving the scroll if you're not working with position: fixed
. I removed it and edited your fiddle: https://jsfiddle.net/mg606dh1/2/
EDIT 2
You can also change the position to position: fixed
and use the code the way you meant for it to be used: https://jsfiddle.net/mg606dh1/3/
Upvotes: 2