Creating a Simple Tooltip jQuery Plugin

 

Reading time: 6 – 10 minutes

In this tutorial we will create a simple but awesome popup tooltip using jQuery. So let’s get started !!

Download

Creating a tooltip in photoshop.

First of all open up photoshop and create a document with dimensions 300 * 150 px, though the dimension may vary on how MUCH data you want show. Tooltips generally show basic and less data. Follow the steps below -

  • Select the rounded rectangle tool with radius 5 px and draw a rectangle with about 15px distance from the canvas margins.
  • This will be our background, now go to fx and add a gradient overlay from #1f1f1f to #ffffff.
  • Now select the drop shadow with options,
    • Blend Mode – normal
    • Opacity – 80%
    • Distance – 0px
    • Size – 21px
  • Now hide the background and export it as png image using Save for Web and Devices option.

That’s it for the photoshop part, Now for the coding part.

Step 1

We will mould our tooltip into a jquery plugin. So first of all we will start will a basic html file to work with and how to show a tooltip for a particular element.

      <html xmlns="http://www.w3.org/1999/xhtml">
           <head>
            <title>jTool</title>
            <link rel="stylesheet" type="text/css" href="jtool.css"  />
            <script type="text/javascript" src="jquery-1.4.2.min.js" ></script>
            <script type="text/javascript" src="jquery.jtool.js"></script>
           <script type="text/javascript">
                $(function(){

                $("a").jTool(); //our plugin

                 });

             </script>
            </head>

        <body>

            <div id="tool">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas ut bibendum orci. Nam scelerisque, risus aliquam pellentesque viverra, libero urna sagittis quam, auctor dictum nunc lectus ut mi.</div>

        <a href="#tool"> Simple Tooltip using jQuery </a>
        </body>
        </html>

First of all we have imported jquery, our plugin and css file which we will create later. Then we have called our plugin on the element we want to show tooltip.

Setting up which tooltip to show on a particular element

To show a particular data on a tooltip we will target the element using href attribute. The href will contain the id of the element which you want to show on hover. That’s what we have done above, div id ‘tool’ is displayed when mouse hovers on anchor with href =’#tool’

Step 2 Working up with the CSS.

Create a css file and name it jtool.css . In this css file we will styling our tooltip elements. The css code could have been set up through jquery but it’s always a good practice to separate logic from presentation. Add the following code in the css.

 #jTool
{
color:#CCCCCC;
padding:5px;
display:none;
max-width:300px;
min-width:130px;
font-family:"Lucida Grande", Tahoma, sans-serif; text-align:justify;
position: absolute;
}

Our tooltip is wrapped by jTool div, we will do that in the js part. It is a basic styling and we will keep minimum width of our tooltip 130px and constraint it to 300px.

#jTool > div
{

padding:10px;
position:relative;
z-index:10;
display:block;

}

#jTool img
{
width:100%;
height:100%;
position:absolute;
padding:0px;
margin:0px;
z-index:1;
}

we have used #jTool img here for styling but there is no image present, actually the image is our background tooltip. It is not possible to scale a background image in CSS, for that we will append image in the jTool div and set its dimension to 100% so that it scales automatically. We will also set its z-index less than div so that text is visible.

Finally our css file looks like.

#jTool
{
color:#CCCCCC;
padding:5px;
display:none;
max-width:300px;
min-width:130px;
font-family:"Lucida Grande", Tahoma, sans-serif; text-align:justify;
position: absolute;
}

#jTool &gt; div
{

padding:10px;
position:relative;
z-index:10;
display:block;

}

#jTool img
{
width:100%;
height:100%;
position:absolute;
padding:0px;
margin:0px;
z-index:1;
}

Step 3 Creating the Plugin

Now create a javascript file and according to jquery plugin naming convection it should be named jquery.plugin.js , so our file name is jquery.jtool.js, First of all we will create a basic structure.

 $.fn.jTool = function(){

    });

Step 4

Now will declare variables and initialize basic settings.

	var element = $(this);
	var tooltip = element.attr("href");
	$(tooltip).wrap("<div id='jTool' />");
    $("#jTool").prepend(<img src='base.png' />");

	 var top = element.offset().top;
	 var right = $(window).width() - element.offset().left;
	 var x,y;

Here first we get the object triggering the tooltip in the element, since we have used href to target elements, we will get the actual tooltip by getting element’s attribute. Then we will wrap it jTool div and prepend our background image.

After that we will get the element’s top position with respect to window and also calculate the length between widow’s width and element’s left position.

Note: Reason for calculating top position and left length is that later we will make our plugin little smart :) .

Step 5

Now we will fade In the tooltip on element’s hover state.

element.hover(function(event){

						  x = event.pageX;
						  y = event.pageY;

						  $("#jTool").css({left:x,top:y});

                          setTimeout(function(){  $("#jTool").stop(true,true).fadeIn("slow"); },200);
							   },
					  function(){
						 $("#jTool").fadeOut("slow");

				});

Now on hover event, we get the mouse’s position and set the jTool position. After a 200ms delay we then show the tooltip.

Step 6

There is a problem, if the element showing the tooltip is either at top left or right corner, then tooltips will be out the viewport so we will make it little smarter.

   if($("#jTool").height()<top)
   y = y-$("#jTool").height()-20;

   if($("#jTool").width()>right)
   x = x-$("#jTool").width();

If distance from the top of the element and window is less than tooltip’s height, it will show towards the bottom and similarly if the difference between window’s width and element’s left position is less than tooltip’s width it will show towards the right.

Step 7

Though the plugin works fine, but as usual it doesn’t look properly in IE, The tooltip’s image isn’t displayed to cover the whole text of the tooltip. Since IE6 is almost extinct, we will make in compatible for IE7. To get around this, we will force the jTool’s image to cover the height of the tooltip.

   if($.browser.msie&amp;&amp;parseInt(jQuery.browser.version)
    $("#jTool img").height($("#jTool").height());

Step 8

Finally our js code looks like.

$.fn.jTool = function(){

		var element = $(this);
		var tooltip = element.attr("href");
		$(tooltip).wrap("<div id='jTool' />");

		 $("#jTool").prepend("<img src='base.png' />");

		 var top = element.offset().top;
		 var right = $(window).width() - element.offset().left;
		 var x,y;

		element.hover(function(event){

						  x = event.pageX;
						  y = event.pageY;

							if($("#jTool").height()<top)
							y = y-$("#jTool").height()-20;

							if($("#jTool").width()>right)
							x = x-$("#jTool").width();

                                $("#jTool").css({left:x,top:y});

                        if($.browser.msie&&parseInt(jQuery.browser.version)<8)
                           $("#jTool img").height($("#jTool").height());

				        setTimeout(function(){

                            $("#jTool").stop(true,true).fadeIn("slow"); },200);
							   },
					  function(){
						 $("#jTool").fadeOut("slow");

				});

	}

We have finally created our tooltip which is lightweight 2kb js size and 1 kb tooltip image and with a good looking UI .

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Add to favorites
  • Design Float
  • DZone
  • email
  • FriendFeed
  • PDF
  • Propeller
  • Reddit
  • RSS
  • StumbleUpon
  • Twitter

Related posts:

  1. 3 Screencasts For Building Your Own jQuery Plugin
  2. Working with the jCrop Plugin
  3. Animate Text with jQuery Easing (screencast)
  4. Validate your forms with ease using jQuery!
  5. Build a Content Slider with jQuery


Written by Abhin Sharma

Abhin Sharma - I am web developer from Udaipur (city of lakes) ,India who loves to work with Java, Mashups and sometimes PHP. I specialize in Swings and JEE. While not programming I love to hang out my friends.

 

3 Responses to “Creating a Simple Tooltip jQuery Plugin”

  1. Bernal Says:

    April 20th, 2010 at 6:43 pm

    Thank you for your tutorial. Could you tell me how can I apply this tutorial to change my wordpress blogroll? I want the description text to be displayed as a tooltip.
    Thank you.

  2. Deanne Falcon Says:

    May 1st, 2010 at 5:30 pm

    Your post is solid. There are some issues here but don’t have the time right now. I’m bookmarking this url and leave this comment to check again later and update my first comment (this one). By the way i found your blog post as i was quering for relevant subjects in Bing

  3. طراحی سایت Says:

    June 14th, 2010 at 8:23 am

    Check out this very simple tooltip also, it can show you content from another file as well as us id tag to save link data, it also support images so that you can also show images on you tooltip, and it moves with mouse pointer.

    http://intekhabrizvi.wordpress.com/2010/01/21/jquery-very-simple-tooltip-plugin-ajax-enabled-2/

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

 
connect with me!