jQuery Horizontal Tooltip

by sixfoottallrabbit | Posted in JavaScript

It can often be useful to present more information to your visitors when they hover their cursor over an element on your website. It’s important to do this effectively without breaking away from the structure of your page – so that’s what we’re gonna do. 🙂

We have a LIVE DEMO of the result for you to play with.

Getting Started

This tutorial won’t take much to get going.

Just download the script from the jQuery website, save it to the same directory as your page and link to it from within your <head> tag with the following HTML:

<script type="text/javascript" src="jquery.js"></script>

Make sure you change the file name to point to the file that you downloaded.

The Tooltip

First, let’s make the tooltip. Here’s an image of what it should look like:

What the tooltip should look like

This consists of 4 parts:

  • The left side of the tooltip which has curved corners
  • The center of the tooltip which contains the tip itself
  • The right side of the tooltp like the left
  • The arrow

The HTML, therefore, looks something like this:

<div class="tip tooltip">
 <div class="left"></div>
 <div class="center">&nbsp;&nbsp;&nbsp;</div>
 <div class="right"></div>
 <div class="arrow"></div>
</div>

Note that I’ve filled the center in with spaces so that it looks normal when first created (we’ll be replacing the spaces eventually though). Also remember the second class of the outer div, ‘tooltip’, because we’ll need it.

And here is the CSS, which makes it look the way it should do:

.tip {
 position: absolute;
 left: -200px;
 z-index: 1;
}

.tip .left, .tip .right{
 float: left;
 width: 6px; height: 22px;
}

.tip .left { background-image: url('tip_left.png'); }
.tip .right { background-image: url('tip_right.png'); }

.tip .center {
 float: left;
 display: block;
 height: 14px;
 padding: 4px 4px 4px 2px;
 background-color: #222;
 color: #fff;
 font-size: 12px;
}

.tip .arrow {
 clear: both;
 margin-left: 10px;
 width: 13px; height: 10px;
 background-image: url('tip_arrow.png');
 background-repeat: no-repeat;
}

A few things to take into account. I’ve set the left position of the tip to -200px. This is to hide it off screen before we start using it. Later, this position will be good for leading into a nice sliding effect.

Also there are three images used in this CSS. They are the rounded ends of the tooltip and the arrow. You can download those here:

Images (zip, 2KB)

The Items

We’re going to create a list to house our elements which will be treated with the tooltip wizardry:

<ul>
 <li><a href="#" class="tooltip" id="item1">Item #1</a></li>
 <li><a href="#" class="tooltip" id="item2">Item #2</a></li>
 <li><a href="#" class="tooltip" id="item3">Item #3</a></li>
</ul>

There’s nothing too fancy about this list. You just have to understand the naming scheme. The class of these items ties them all to the same tooltip, which we named earlier. The id of each item ties them to the message that will be displayed in their tooltip and so must be unique. You can name these classes and ids however you like, as long as you remember them for later.

The Tooltip Class

Time to write the JavaScript that makes all this work. And we’re doing it object-oriented. Eek, object-oriented JavaScript.

Classes in JavaScript are essentially just functions. The structure of a function, our class, can be manipulated through use of the this keyword. Our Tooltip class will take a couple of arguments and initialise a few member variables:

function Tooltip(elementClass, tipMessages) {
    var obj = this;
    this.m_class = elementClass;
    this.m_messages = tipMessages;
    this.m_tipDiv = $(".tip."+elementClass);

    // WE'LL DEFINE METHODS HERE //

    $("." + this.m_class).mouseover(this.show).mouseout(this.hide);
    this.m_tipDiv.hide();
}

First we create a reference to the current object. This will be used within methods later on because jQuery will override the reference to this.

Then we initialise some properties of our class. The class property will store the class name that we used to link all of our items together. The messages property will contain an associative array that links the items to their messages. We get a reference to the the tip element that we created earlier and store it in the tipDiv property.

Now after the space I’ve left out for the methods, we set the mouseover action to point to a method called show() and the mouseout action to point to hide(). These methods will do exactly what you expect; show and hide the tooltip. Then lastly we initially hide the div, ready for action.

Now we’ll define the methods as follows:

    this.show = function () {
        // Get the message from the associative array
        var message = obj.m_messages[$(this).attr("id")];
        if (!message) message = "Tip undefined for "+$(this).attr("id");

        // Animate the tooltip
        obj.m_tipDiv.show().css("top",$(this).offset().top - 34)
            .stop(true,false).animate({left: $(this).offset().left + ($(this).width() / 2) - 16})
            .find('.center').html(message);
    }
    
    this.hide = function () {
        // Make the tooltip fly away
        obj.m_tipDiv.stop(true,false).animate({left: -200});
    }

It is important to note that this now refers to the element that we’re hovering over and obj is the Tooltip object.

The show method is fairly simple. We just get the message from the associative array by using the item ID as reference. We then animate the tipDiv so that it flies in from it’s current position to just above the element.

The hide method is even more simple, as it just makes the tipDiv fly back off the screen.

Let’s go

Now to get this to start working, we’ll set up an associative array with all the messages in and then create the Tooltip object to handle it all:

$(document).ready(function () {
    var tips = { item1: "First tooltip",
                 item2: "Second tooltip",
                 item3: "Third tooltip"};
    new Tooltip('tooltip',tips);
});

As you can see, the associative array consists of the item IDs and the message associated with them. Pretty simple. Then we pass that along with the class name that binds them all together to a new Tooltip object.

And voila. You’re done. 🙂