Search code examples
jquerytooltipqtip

how to make tooltip follow cursor


How to get a tooltip to follow the cursor. My tooltip appears on the right bottom. Just a piece of it appears:

image

Here's the code:

$(document).ready(function(e) 
{
    // By suppling no content attribute, the library uses each   elements title attribute by default
    $('#visualization').qtip({
        // Simply use an HTML img tag within the HTML string
        content: 'i am a qtip'
    });
});

Solution

  • I don't know anything about qtip as a library, but first I'd check to see if they have any options to pass in to achieve this behavior. Even if they do, it's good to know how things work anyways!

    To do it manually, you'd use CSS to give your tooltip element position: fixed; and then use javascript to get the x and y coordinates of your mouse, updating the left and top CSS attributes every time the mouse moves.

    Here is an example!

    $( document ).on( "mousemove", function( event ) {
      $( "#log" ).text( "pageX: " + event.pageX + ", pageY: " + event.pageY );
      $( ".tooltip" ).css({
        "left" : event.pageX,
        "top" : event.pageY
      });
    });
    .tooltip {
    display: inline-block;
    position: fixed;
    padding: .5em 1em;
    background-color: #f1f1f1;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <h4 id="log">pageX: -, pageY: -</h4>
    <div class="tooltip">I'm a tooltip!</div>