1

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'
    });
});
CDspace
  • 2,639
  • 18
  • 30
  • 36
Abd ELL
  • 147
  • 1
  • 4
  • 13
  • 1
    Possible duplicate of [How to make a qtip tooltip move with cursor](http://stackoverflow.com/questions/9608990/how-to-make-a-qtip-tooltip-move-with-cursor) – smarber Mar 14 '17 at 16:35

1 Answers1

7

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>
Jonathan Bowman
  • 1,606
  • 1
  • 12
  • 17
  • I liked your approach a lot. How should one go around to restricting the tooltip to only appearing when mouse cursor is inside a certain div? – parsecer Jan 05 '20 at 17:24
  • 1
    Thanks, and sure! I’m not at my computer, but rather than doing `$(document).on(‘mousemove’, .....`, I THINK you would just use the identifier of your div. So, it would instead read like `$(‘#my-div’).on(‘mousemove’, .....`. See if that does it for you! – Jonathan Bowman Jan 05 '20 at 18:40
  • Thank you for answering so fast! I've managed to add the event listeners and it does react on entering/exiting the divs! I'm trying to make it kinda like on this site: https://auctions.craftlink.xyz/items (just put a mouse on an item name), so the tooltip both moves with the cursor and on enter/exit out of a div. Your answer was the best fitting solution I've found which is refreshingly readable for a beginner like myself! – parsecer Jan 05 '20 at 18:55
  • 1
    This works, but not on scrollable page. Simply add a
    at this code above. Then scroll down and see the tooltip moving away from the mouse's position. For those who seek solution to this, simply use clientX, clientY - instead of pageX, pageY.
    – Black Sun Phoenix Entertainmen May 08 '21 at 23:51