Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML-Tooltip position relative to mouse pointer

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> 
like image 321
Ben Avatar asked Mar 29 '13 12:03

Ben


People also ask

How do you set a tooltip position?

The tooltip text is placed inside an inline element (like <span>) with class="tooltiptext" . CSS: The tooltip class use position:relative , which is needed to position the tooltip text ( position:absolute ). Note: See examples below on how to position the tooltip.

How do I set dynamic position in tooltip?

Dynamic positioning The Tooltip and its tip pointer can be positioned dynamically based on the target's location. This can be achieved by using the refresh method, which auto adjusts the Tooltip over the target.


1 Answers

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;     } }; 
like image 170
Daniel Imms Avatar answered Sep 19 '22 17:09

Daniel Imms