How to create tooltip for element using jQuery?

When mouse movers on an HTML element, a tooltip is popped up displaying some useful information about the element. This sounds cool. Today, we will learn how to add a tooltip for element with jQuery.

<script type="text/javascript" src="jquery.min.js"></script>

<button class="hide tip" data="hello">tip button</button>

<script language="javascript" type="text/javascript">
var xoff = 0; 
var yoff = 30; 
$(".tip").unbind().hover(function(e){ = (e.pageY + yoff);
  this.left = (e.pageX + xoff);
  var data = $(this).attr("data");
    var tipcontainer = '<div class="hide" id="tipcontainer">'+data+'<div>';
    $("#tipcontainer").css({"position":"absolute","top" + "px","left":this.left + "px"}).fadeIn("fast");
  function (e) { = (e.pageY + yoff);
    this.left = (e.pageX + xoff);
    $("#tipcontainer").css({"position":"absolute","top" + "px","left":this.left + "px"});

First, you should style the elements you want to add a tooltip to with a specific CSS class(in our case, the class “tip”). Second, you should prepare the tooltip information for the element as the value of one of its attributes(in our case, the attribute is “data”). Third, you should add jQuery code at the end of the document to make the tooltip. Thanks to the powerful function of jQuery, only one line of code is enough to implement the tooltip. The key jQuery function is hover, which binds two event handlers to the element, one for the mouse enter event and the other for the mouse leave event. When mouse moves onto an element with “.tip” class, the corresponding event handler will create the tooltip element and append it to the “body” element, then display the tooltip element. When mouse moves out of the element, the corresponding event handler will remove the element from DOM. When mouse moves over the element, the corresponding event handler will show the tooltip element at updated positions. Displaying the tooltip element is by CSS “position”, “top”, and “left” properties. It calculates the position of the tooltip by the mouse coordinates (as the parameters of the event and adjusted by an offset so the tooltip won’t be blocked by the mouse pointer).

Comments are closed, but trackbacks and pingbacks are open.