Create simple tooltips with CSS and jQuery – Part 1

CSS Tutorials, Javascript, Tutorials Oct 15, 2008 75 Comments

CSS tooltips are very popular in modern web design and contrary to popular belief it is really easy to create them, especially with one of the all so popular javascript frameworks.

Before I started to delve deeper into this topic, I thought you have to use at least a plugin, but to get some basic tooltips all you need are about 10 lines of CSS and jQuery Code.

This Tutorial will teach you how to create such tooltips with some basic CSS and jQuery.

Creating jQuery Tooltips: the CSS

First of all take a look of what we are going to create (hover over the link block and don’t care about the background, it’s only for better demonstration of the tooltip transparency)

First of all lets take a look at the structure of this tool tip: A typical link will look something like this:

    <a href="#" title="This is a small Tooltip with the Classname 'Tooltip'">Link</a>

We will later use javascript to extract the title and put it into  a <p> and a <div> container:

<div class="tooltip">
    <p>This is a small Tooltip with the Classname 'Tooltip'</p>
</div>

The CSS for our soon to be terrific tooltips looks something like this:

.tooltip{
    position:absolute;
    z-index:999;
    left:-9999px;
    background-color:#dedede;
    padding:5px;
    border:1px solid #fff;
    width:250px;
}

.tooltip p{
    margin:0;
    padding:0;
    color:#fff;
    background-color:#222;
    padding:2px 7px;
}

The Position has to be absolute since as soon as our Javascript is enabled it will set the top and left property of the div to display it next to our mouse cursor.
For now we set the left property to -9999px to move the tooltip out of the view port. The rest of the CSS is only for styling purpose.

Creating jQuery Tooltips: the jQuery Code, short and simple

Lets take a look at the whole script, I will give a step by step explanation afterwards:

function simple_tooltip(target_items, name){
 $(target_items).each(function(i){
		$("body").append("<div class='"+name+"' id='"+name+i+"'><p>"+$(this).attr('title')+"</p></div>");
		var my_tooltip = $("#"+name+i);

		$(this).removeAttr("title").mouseover(function(){
				my_tooltip.css({opacity:0.8, display:"none"}).fadeIn(400);
		}).mousemove(function(kmouse){
				my_tooltip.css({left:kmouse.pageX+15, top:kmouse.pageY+15});
		}).mouseout(function(){
				my_tooltip.fadeOut(400);
		});
	});
}
$(document).ready(function(){
	 simple_tooltip("a","tooltip");
});

This may look intimidating, especially if you are new to jQuery but its really simple. First of all we create the function:

function simple_tooltip(target_items, name){
}

↑ The target item is a variable we will define when calling the script.For example: to append the tooltips to all links in container #maincontent you would enter “#maincontent a”. The name defines the css class we use to style the tooltip. We use variables here for flexibility purpose so you can add diverent tooltips with different stylings.

function simple_tooltip(target_items, name){
  $(target_items).each(function(i){
     // generates code for each tooltip
  });
}

↑ This each loop will generate the code for every item that is found by our script. The variable i which we are passing in the function will be automatically incremented by jQuery after each iteration. This way we will be able to give the tooltips unique ids.

function simple_tooltip(target_items, name){
 $(target_items).each(function(i){
	$("body").append("<div class='"+name+"' id='"+name+i+"'><p>"+$(this).attr('title')+"</p></div>");
	});
}

↑ This line creates the html code for each tooltip. They all get the same Classname but different ids. The title is added inside of the div and p container

function simple_tooltip(target_items, name){
 $(target_items).each(function(i){
	$("body").append("<div class='"+name+"' id='"+name+i+"'><p>"+$(this).attr('title')+"</p></div>");

         var my_tooltip = $("#"+name+i);

        });
}

↑ This line selects the tooltip via jQuery and saves it to a variable for later use

function simple_tooltip(target_items, name){
 $(target_items).each(function(i){
	$("body").append("<div class='"+name+"' id='"+name+i+"'><p>"+$(this).attr('title')+"</p></div>");
         var my_tooltip = $("#"+name+i);

                $(this).removeAttr("title").mouseover(function(){

		}).mousemove(function(kmouse){

		}).mouseout(function(){

		});

        });
}

↑ This is the basic construct of our functions centerpiece. First of all we select the current link with $(this). Then the title attribute is removed since we don’t want to display the “normal” tooltip that every browser displays when hovering over links.
Then we prepare 3 functions:

  • The mouseover function is called when you first hover over the link
  • The mousemove function is called when we move the mouse while hovering over the link
  • The mouseout function is called as soon as the mouse leaves the link

As you can see we pass a parameter in mousemove: this parameter is very important since it stores the position of the mousecursor!

$(this).removeAttr("title").mouseover(function(){
			my_tooltip.css({opacity:0.8, display:"none"}).fadeIn(400);
		}).mousemove(function(kmouse){
			my_tooltip.css({left:kmouse.pageX+15, top:kmouse.pageY+15});
		}).mouseout(function(){
			my_tooltip.fadeOut(400);
		});

↑ Now we define whats happening when the different functions are called:
On mouseover we set some css values for the tooltip: we define the transparency and set the  display to none. Then the div slowly fades in because of the fadeIn call.

On mousemove we constantly set the positioning values left and top to align the tooltip next to the cursor. the X and Y coordinates are called via .pageX and .pageY. We also add a little offset of 15 px so the tooltip is not directly below the cursor

On mouseout we simply call fadeOut to hide the tooltip

$(document).ready(function(){
	 simple_tooltip("a","tooltip");
});

↑ Last thing we do is: we call the script as soon as the document is loaded. As mentioned earlier parameter 1 is the selector and parameter 2 is the classname of our tooltip. This way you can create multiple designs for your tooltips.

The code  we just created can be modified in various ways. I have used a modified version for images in a lately created showcase wordpress theme for Themeforest.net.

Thats is, have fun creating your own sleek tooltips ;)

Update:

Suggested by my readers here is a version of the script that checks if the link has a tittle:

function simple_tooltip(target_items, name){
 $(target_items).each(function(i){
		$("body").append("<div class='"+name+"' id='"+name+i+"'><p>"+$(this).attr('title')+"</p></div>");
		var my_tooltip = $("#"+name+i);

		if($(this).attr("title") != ""){ // checks if there is a title

		$(this).removeAttr("title").mouseover(function(){
				my_tooltip.css({opacity:0.8, display:"none"}).fadeIn(400);
		}).mousemove(function(kmouse){
				my_tooltip.css({left:kmouse.pageX+15, top:kmouse.pageY+15});
		}).mouseout(function(){
				my_tooltip.fadeOut(400);
		});

		}
	});
}

$(document).ready(function(){
	 simple_tooltip("a","tooltip");
});

Update 2:

Here is part 2 of the Tutorial: Create simple tooltips with CSS and jQuery – Part 2: Smart Tooltips

75 Responses to “Create simple tooltips with CSS and jQuery – Part 1”

  1. Jan says:

    Hey Christian or Kriesi.

    Thank your for such a good tutorial!
    It’s really nice to know that you can make yourself a tooltip with less css and javascript skills.

    I will definitly use it on my website.

  2. Ash says:

    Pardon,
    But it is not working in firfox3.03.

  3. Kriesi says:

    Works perfect for me in firefox 3.03 for me, both on WinXP and MacOSX :/

  4. John Churchill says:

    This is a pretty nice tooltip script. One thing I didn’t like about it AT FIRST was that I thought I’d have to provide a title attribute for every link on my page or I’d get an empty tooltip box when hovering over a link.

    I discovered I could change the script slightly to include a class attribute on the anchor and that would limit the effect to only the ones that I had supplied the class for. The new class was “_tooltip” to keep it separate from the existing “tooltip” class.

    Then I took it a step further and styled different tips adding 2 more classes “_tooltip2″ and “_tooltip3″.

    The only modifications to the script above come at the very end …

    $(document).ready(function(){
    simple_tooltip(“a._tooltip”,”tooltip”);
    simple_tooltip(“a_tooltip2″,”tooltip2″);
    simple_tooltip(“a._tooltip3″,”tooltip3″);
    });

    and of course I have to modify my css accordingly:
    .tooltip, .tooltip2, .tooltip3 {
    position:absolute;
    z-index:999;
    left:-9999px;
    background-color: #dedede;
    padding:5px;
    border:1px solid #fff;
    width:150px;
    }
    .tooltip p, .tooltip2 p, .tooltip3 p {
    margin:0;
    padding:0;
    color:#fff;
    padding:2px 7px;
    }
    .tooltip p {
    background-color:#C16C29;
    }
    .tooltip3 p {
    background-color: green;
    }

  5. Kriesi says:

    you are using the script exactly the way I thought it should be used =)

    You can of course add an if statement and check i a title is available at the beggining of the script

    Something like this:
    if($(this).attr(‘title’) == “”){return false;}

  6. Ricochet says:

    Hi, great script!
    I’m quite the novice to jQuery (and js in general, to be honest), but I already love it big time. The only problem is that because of that, I can find it a bit tricky to customize scripts.

    I liked the idea of the added statement checking for titles first, but I can’t seem to make it work. Is it really just to add it to the beginning of the script? I’ve done that, and it gives me nothing…

  7. Kriesi says:

    the one line I threw in was just an idea (that doesn’t work all too good, i must admit^^), I have updated the tutorial, you can find the whole updated script at the end.

    It now checks if a title is set and should work without problems.

  8. Ricochet says:

    I don’t know if I’m doing something wrong, but even with that new script, there are tooltips on all links, even those without titles.

  9. Kriesi says:

    This should work as you can see here:
    http://www.kriesi.at/wp-content/extra_data/tooltip_tutorial/step3.html

    If you are working on a live site maybe I can help you if tell me the url.

  10. Kriesi says:

    guess this could be because you are using an old version of jquery. I have only tested my script with v.1.2.6, You are using 1.2.2 which is pretty old =)

    Maybe you should consider updating it =)
    Another option i guess would be to change the if statement to:

    if($(this).attr(“title”) != “” || $(this).attr(“title”) != “undefined”){ etc

  11. Ricochet says:

    Okay, thanks I’ll try if updating jQuery helps :)

  12. Ricochet says:

    I think I found the problem! I had two conflicting jQuery files, one that was 1.2.6, and one that was 1.2.2
    arr, sloppy coding on my side, I’m glad everything works now now. Thanks for your help!

  13. riper says:

    great post ! thanks !

  14. Monkeytail says:

    (Y)++

  15. th3.d34th says:

    Hey,

    I used it on my site (just a fun project to learn a little bit xhtml and css) and I’m searching a possibility to slide the tooltips to the left side if they would otherwise showed outside of the browser-window (for example with the resulution of 1024×768 the tooltips at the right side are not showed inside the window).

    Do you have an idea?

  16. Kriesi says:

    Already did it, cause I needed the same =)
    I am going to release Part 2 of this tutorial during the upcoming days ;)

  17. th3.d34th says:

    Perfect :D thank you very much!

  18. eduardo says:

    I’m currently trying to throw this tooltip into my site but can’t seem to get it working at all. Is there a zip file or anything that you can download full functioning files. I’ve tried looking at the source code but still doesn’t seem to work.

    Thank you.

  19. Biberon says:

    I tried to see it work on different sites named here by your fans. on FF 3.0.5 I use now it is not always running. Same for other browsers although it works nice on th3.d34th’s website.

    Anyway I like the tooltip alot. Best of wishes to you and keep up the nice work ;)

  20. Alain says:

    Just, It’ll be wonderfull if you show me some ToolTip that work’s on IExplorer, I try to put it on a list or comboBox, but I can’t find the tool for this action… greetings man!!!

  21. Online Trivia says:

    Great Tutorial! I will implement it in all my sites, thanks a lot :)

  22. webweaver says:

    Thanks for the tutorial – I’ll be trying version 2 tomorrow…

    One problem I’m having is that in FF the tooltip moves rather jerkily, and it’s possible to catch up with the tooltip with your mouse (even though it’s supposed to be positioned above the mouse).

    Once you’ve caught up with the tooltip and you are hovering over it, it flickers like crazy – I guess as it goes into a loop of animating the fadeIn/fadeOut function.

    I’ve tried adding a .stop to both the animation lines, but it’s still not working brilliantly. Am I doing it right? Is there a better way of doing it?

    Here’s my code:

    function simple_tooltip(target_items, name){
    $(target_items).each(function(i){
    $(“body”).append(“”+$(this).attr(‘title’)+”");
    var my_tooltip = $(“#”+name+i);

    $(this).removeAttr(“title”).mouseover(function(){
    my_tooltip.css({opacity:1, display:”none”}).fadeIn(400).stop(false,true);
    }).mousemove(function(kmouse){
    my_tooltip.css({left:kmouse.pageX-21, top:kmouse.pageY-36});
    }).mouseout(function(){
    my_tooltip.fadeOut(400).stop(false,true);
    });
    });
    }

  23. Jenitha says:

    Hi,
    I have a pblm in tooltip, I want a tooltip differing from one to another in the dropdown.

    Can someone help me in doing this.

    Thanks in advance,
    Jenitha

  24. Marv says:

    Thanks for this great tutorial!

  25. Bruno Brás says:

    Hey Kriesi,

    Don’t you remember me ? I was the guy that bought Design Showcase :)

    Well, I’m a really noob on jQuery, so I can pay you for adding the tooltips for my website. I really need it.

    Best Regards,
    Bruno Brás.

  26. DonKeyBawlZ says:

    I would like to add that the import order is VERY important.

    Always import the jQuery lib first, the .css always goes before if it might be used by scripts.

  27. Jordan Garn says:

    Brilliant! I was trying to think of an easy way to do this and this is probably the easiest best Tooltip tutorial around, thanks!

  28. hatemgamil says:

    hi all i want to make a stylish tool tip with jquery
    ,,its data comes from database
    for example
    i have a datalist that gets the name of employees from data base
    and i want when i mouseover each name the id of this employee appears in a tool tip ,,plz help
    thnx

  29. Pavel says:

    Great job! Thank you!

    PS. I think that hard-coded width of a tooltip is not very good. But as we know, IE6 doesn’t understand max-width css property. This can easily be solved with javascript. Just add this line to the simple_tooltip() function:

    if(my_tooltip.width() > 450) my_tooltip.css({width:”450px”});

Click to show trackbacks

  1. Simple tooltips with CSS and jQuery - Kreativuseâ„¢ - Creative Resources and Inspirations
  2. vBharat.com » Create simple tooltips with CSS and jQuery
  3. pligg.com
  4. Here I go » Tag, you’re it!
  5. csskit.net
  6. Create Simple Transparent Tooltips with CSS and jQuery
  7. Web Developer and Designers Resources | Voxnio» Blog Archive » Simple Transparent Tooltips with jQuery and CSS
  8. gearhed.com » Blog Archive » Best of the web - my pick for October 2008
  9. Create simple tooltips with CSS and jQuery | Kriesi.at - new media design | Enjoy News, Feeds & Share All Your Favorite Media Online With The Rest Of the World… Video, TV, Shows, Music, Audio, Pictures, Images, Games, News, Feeds, Links, www.CLH
  10. Best of the web - my pick for October 2008 | zbStudio.net
  11. DIGITALife » CSS and jQuery Tooltip + WP Tutorials
  12. souldanse » Blog Archive » links for 2009-01-10
  13. 30 Tooltip scripts | Web Tutorials
  14. jQuery - customised tooltips displaying the title of the link « DocuView - document management system
  15. 5 tutoriales para crear tooltips con Jquery | ElWebmaster.net
  16. jQuery Tutorial – Create simple tooltips with CSS and jQuery | jQuery Wisdom
  17. 40 Free Amazing jQuery Plugins and Tutorials With Demos | DesignBeep
  18. 40 Free Amazing jQuery Plugins and Tutorials With Demos | Afif Fattouh - Web Specialist
  19. jQuery Tooltips - Gaunau.com
  20. WordPress Arena: A Blog for WordPress Developers, Designers and Bloggers
  21. Useful Tool Tips Tutorials and jQuery Plugins | AlexVerse
  22. ??CSS?jQuery???????
  23. Best jQuery Plugins
  24. 29 Amazing JQuery Plugins | Designer's Place
  25. 150 best jQuery effects for web designers and developers « Web Design Blog – WebDesignShock
  26. Saurabh Odhyan's Blog » Create simple tooltips with CSS and jQuery