jQuery tooltip

Sorry for the lack of updates recently but I have been swept off my feet with work. A couple days ago we rolled out an update to Centation’s website 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.


Let’s start with some nice semantic markup.

<div class="container">
    <div class="hover">
        <p>Hello. I'm a tooltip.</p>
        <a href="page.html"><img src="image.jpg" alt="Image alt" /></a>

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() {
    // User has hovered over the container, show tooltip
    $(".container").hover(function() {
        // Are we already displaying the tooltip?
        if ($(".hover", this).css("display") == "block") { return false; }

        // Get the offset of the element...
        os = $(this).offset();

        // ... and position it, and animate it to its new location
        $(".hover", this)
            .css({top:"px", left: os.left+60+"px"})
            .animate({top:"px", opacity: "show"}, 750);
    // And then remove the hover effect once we are no longer hovered over
    function() {
        // Get the offset...
        os = $(this).offset();

        // ... and animate it back to its original position
        $(".hover", this).animate({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 initially 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.