HTML-Tooltip position relative to mouse pointer

alignment, css, html, mousehover, tooltip

Solution

For default tooltip behavior simply add the `title` attribute. This can't contain images though.

<div title="regular tooltip">Hover me</div>

Before you clarified the question I did this up in pure JavaScript, hope you find it useful. The image will pop up and follow the mouse.

jsFiddle

JavaScript

var tooltipSpan = document.getElementById('tooltip-span');

window.onmousemove = function (e) {
    var x = e.clientX,
        y = e.clientY;
    tooltipSpan.style.top = (y + 20) + 'px';
    tooltipSpan.style.left = (x + 20) + 'px';
};

CSS

.tooltip span {
    display:none;
}
.tooltip:hover span {
    display:block;
    position:fixed;
    overflow:hidden;
}

Extending for multiple elements

One solution for multiple elements is to update all tooltip `span`'s and setting them under the cursor on mouse move.

jsFiddle

var tooltips = document.querySelectorAll('.tooltip span');

window.onmousemove = function (e) {
    var x = (e.clientX + 20) + 'px',
        y = (e.clientY + 20) + 'px';
    for (var i = 0; i < tooltips.length; i++) {
        tooltips[i].style.top = y;
        tooltips[i].style.left = x;
    }
};

Problem

How to align the tooltip the natural style: right bottom of the mouse pointer? ``` <!DOCTYPE html> <html> <head> <title>Tooltip with Image</title> <meta charset="UTF-8"> <style type="text/css"> .tooltip { text-decoration:none; position:relative; } .tooltip span { display:none; } .tooltip span img { float:left; } .tooltip:hover span { display:block; position:absolute; overflow:hidden; } </style> </head> <body> <a class="tooltip" href="http://www.google.com/"> Google <span> <img alt="" src="http://www.google.com/images/srpr/logo4w.png"> </span> </a> </body> </html> ```

Original source