jQuery tooltip
Sorry for the lack of updates recently but I have been swept off my feet with work. A couple days ago I redesigned part of my companies website, Centation, whereby I needed to make a little jQuery tooltip to add a dynamic flair to the page. Well, I didn’t need to make one, but the lack of quality jQuery tooltip plugins forced me to. I thought I would give you the code of how I did this, and give you a couple demonstrations.
The HTML
Let’s start with some nice semantic markup.
- <div class="container">
- <div class="hover">
- <p>Hello. I'm a tooltip.</p>
- </div>
- <div>
- <a href="page.html"><img src="image.jpg" alt="Image alt" /></a>
- </div>
- </div>
We have a container which will contain the tooltip and the text/image/anything which you want a tooltip to appear when hovered over. I have put the tooltip in a div with the class hover. Nice simple stuff.
The jQuery
Obviously wee need the jQuery core, but we also need this little bit of jQuery:
- $(document).ready(function() {
- $(".container").hover(function() {
- if ($(".hover", this).css("display") == "block") { return false; }
- os = $(this).offset();
- $(".hover", this).css({top: os.top+"px", left: os.left+60+"px"}).animate({top: os.top-60+"px", opacity: "show"}, 750);
- },
- function() {
- os = $(this).offset();
- $(".hover", this).animate({top: os.top+"px", opacity: "hide"}, 500);
- });
- });
It might look a bit of a mess, and I would agree with you there, but there is logic in this. The only bits of this code you need to understand and change are the CSS positioning and the animates.
The CSS intially places the hover in the correct position using the position of the hovered over element. You can change this to make the hover appear a little bit high, lower, to the left, to the right, or any combination of those.
The animation says where the hover element will move to. Again we use the offset of the hovered over element to base our position. As with the CSS positioning we can set it to go to the top, right, bottom or left.
What does it look like in action?
It looks great. I have created a demo page with two examples, and you can se the effect of this on my companies, Centation, portfolio.

1 Smithy wrote
21st June, 2008
Very nice. I espcially like the check to make sure that the tooltip isn’t already shown before animating it, most tips don’t do this which can result in multiple tooltips popping up or a continuous stream one after the other.