1

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'));
})

DEMO

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 :)

It worked yesterday.
  • 4,507
  • 11
  • 46
  • 81
  • http://james.padolsey.com/jquery/#v=git&fn=jQuery.fn.offset – klenium Aug 25 '15 at 15:17
  • @klenium I don't see any mention of jQuery in his/her post. – Mulan Aug 25 '15 at 15:32
  • @naomik I know, that's why I posted it as a comment, however, jQuery's source is always good to learn how thigs should work. – klenium Aug 25 '15 at 15:42
  • It might be worth looking in to [`getBoundingClientRect()`](https://developer.mozilla.org/en/docs/Web/API/Element/getBoundingClientRect). Also simply add `pageYOffset` to the `y`, and `pageXOffset` for the `x`. – Daniel Apt Aug 25 '15 at 16:27

1 Answers1

2

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/

Robin Dorbell
  • 1,569
  • 1
  • 13
  • 26