I am trying to create a tooltip for a navigation bar, the code is below. I'd like to have the div follow the mouse cursor, which function is needed to achieve this?
$('div#navigation a').hover(function() {
$('div#tooltip').fadeIn(500)
}, function() {
$('div#tooltip').fadeOut(100)
});
On mousemove get the mouse event coordinates pageX and pageY
var $tooltip = $("#tooltip");
$(document).on("mousemove", function(evt) {
$tooltip.css({left: evt.pageX, top: evt.pageY});
});
#tooltip{position:absolute;background:red;width:20px;height:20px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tooltip"></div>
Here's a basic plugin example
(function($) {
var moveTooltip = false,
$tooltip = $("<div/>", {
appendTo: "body",
id: "tooltip",
css: {
position:"absolute",
display:"none",
zIndex:99999,
maxWidth:160,
padding:10,
background:"#eee"
}
});
$(document).mousemove(function(ev) {
if(!moveTooltip) return;
$tooltip.css({top: ev.pageY+15, left: ev.pageX+15});
});
$.fn.tooltip = function() {
return this.each(function(){
$(this).hover(function() {
moveTooltip = true;
$tooltip.html($(this).data('tooltip')).fadeTo(300, 1);
},function(){
moveTooltip = false;
$tooltip.hide();
});
});
};
}(jQuery));
$("nav a").tooltip();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav>
<ul>
<li><a href="#" data-tooltip="This is my title 1">Link 1</a></li>
<li><a href="#" data-tooltip="This is my title 2 ">Link 2</a></li>
<li><a href="#" data-tooltip="<b>This</b> is my title 3.<br>A new line">Link 3</a></li>
</ul>
</nav>
Note: you might want to further improve on that code restricting the position of the tooltip to the viewport boundaries, you got the idea.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With