Simple and Easy Tooltip Using jQuery & CSS3

I love jQuery and the way it makes web-designer’s/developer’s life easier.  Although it took all a while to accept it. I still prefer to write my own stuff, I can’t deny its advantages.   Today I will show you a “Tool-Tip” examples of using the same very, very simple script.

Features and Principle

Note: Tooltip Plugin is Less than 1Kb in size.
What this script does is adds an element to the body when you roll over a certain object. That element’s appearance is predefined with css (positioned absolute and styled) so all we need to do is fill the element with content, calculate mouse position and make it move accordingly. When cursor is moved over he object, element moves with it and when cursor roll out, the element is deleted.

Here is a  example where you can see this script in action.

The Simplest jQuery Tooltip Ever

The script takes a title attribute of an A tag and place it inside the popup element.

The Html

<a href="https://dhirajkumarsingh.wordpress.com" class="tooltip" title="Latest Techonology Updates in Web Technology">Roll over for tooltip</a>

The CSS

#tooltip{
	position:absolute; 
        color:#fff; 
        display:none;
	border:1px solid #333; 
        border-radius:4px;
	background-color:#222; background:rgba(2,2,2,.8);
	padding:2px 5px; 
        box-shadow:2px 2px 5px 0 rgba(2,2,2,.8);
}

jQuery – The javascript

First of all, we have to add jQuery library.
after adding jQuery library we have to add this tooltip plugin.
In this plugin you will got :

this.tooltip = function(){	
	/* CONFIG */		
		xOffset = 10;
		yOffset = 20;		
		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result		
	/* END CONFIG */		
	$("a.tooltip").hover(function(e){											  
		this.t = this.title;
		this.title = "";								  
		$("body").append("

“+ this.t +”

"); 
                $("#tooltip") .css("top",(e.pageY - xOffset) + "px") 
                              .css("left",(e.pageX + yOffset) + "px") 
                              .fadeIn("fast"); 
         }, function(){ this.title = this.t; 
                  $("#tooltip").remove(); 
         }); 
         $("a.tooltip").mousemove(function(e){ 
                $("#tooltip") .css("top",(e.pageY - xOffset) + "px") 
               .css("left",(e.pageX + yOffset) + "px"); 
}); 
}; 
// starting the script on page load 
$(document).ready(function(){ 
              tooltip()
});

view demo

Your turn

I hope you enjoyed this article and the techniques I used. Please share your comments and questions below!

Posted by: Dhiraj kumar

2 thoughts on “Simple and Easy Tooltip Using jQuery & CSS3

Leave a comment