1
votes

I'm working a but of code that is supposed to add a "tooltip" that follows the mouse as you hover over a div. (it's supposed to do this to 3 sets of 8 divs)

The content of the tooltip is placed in a span, which in turn is inside the 'li' that has the .hover and .mousemove attached to it.

A "live example" of what I'm trying to accomplish can be seen here. (still in development, tooltip should be seen when hovering the red bars).

http://staging2.e2e.be/ciber4/15-werfzones--de-werven-op-een-rij/zoek-op-planning

Basically, i just need the tooltip to be relative the red blocks, and not relative to the body?

Also made a fiddle with the corresponding code.

http://jsfiddle.net/JDST8/

2
i don't think so.... (i didn't ask that question at least, I'll see if somehow I can find the answer there though) - Jbcarey

2 Answers

2
votes

You can use $(selector).position() to get the X/Y coords of the bar. It returns an object with "top" and "left" keys containing the element's full page offset.

Here's a fiddle with a working example: http://jsfiddle.net/xJSMu/

PS: You got your x and y offsets the wrong way round in your fiddle - by names anyway.

PPS: I've also added some selector caching (Rule of thumb: if you use it more than once, cache it instead of calling the jQuery constructor again).

1
votes

HTML

<div id="tooltipWindow" class="tooltipContainer">
    <div></div>
</div>

CSS (Add styles as you want, in the script below I have also added the attached element's class to the tooltip div)

<style>
    .tooltipContainer {
        position: fixed;
        height: auto;
        width: auto;
        background: ghostwhite;
        padding: 10px;
    }
</style>

JAVASCRIPT (jQuery, dont forget to include the jQuery library, I have added the include tag as well)

<script src="https://code.jquery.com/ui/1.10.4/jquery-ui.min.js" type="text/javascript"></script>
<script>
    //Following Tooltip
    $('.elementClassName').mousemove(function(e) {
        if ($(this).attr('title') != "") {
            $('#tooltipWindow div').html($(this).attr('title'));
            $('#tooltipWindow').css('left', e.clientX + 10).css('top', e.clientY + 10).addClass($(this).attr('class'));
            $('#tooltipWindow').show();
        }
    });
    $('.elementClassName').mouseleave(function (e) {
        $('#tooltipWindow').hide();
        });
    }

    //Non Following Tooltip
    $('.elementClassName').hover(function(e) {
        if ($(this).attr('title') != "") {
            $('#tooltipWindow div').html($(this).attr('title'));
            $('#tooltipWindow').css('left', e.clientX + 10).css('top', e.clientY + 10).addClass($(this).attr('class'));
            $('#tooltipWindow').show();
        }
    },function (e) {
        $('#tooltipWindow').hide();
        });
    }

</script>