Web development by Gabriele Romanato

Post navigation

jQuery tooltips tutorial

In this post I'm going to show you how to implement a series of basic tooltips using jQuery. As you will see, there's nothing difficult in this and I hope I'll be clear enough to explain it correctly. What are tooltips? Tooltips are boxes that popups when a user activates some links or other controls. Instead of being intrusive as real JavaScript popups, tooltips are pure HTML boxes with some CSS styles attached to them. So let's say that we have a series of HTML links. We want that on each link a tooltip appear when a user hovers the link with the mouse and then this tooltip should disappear when the mouse is moved away from the link.

Further, the tooltip should contain the value of the title attribute of each link. For that reason, we have to remove this attribute before showing the tooltip. If we don't do so, there will be two tooltips per link, and that's not what we want. As I said earlier, tooltips need to be stylized with CSS. So here are our styles:

We're using absolute positioning here because we actually need that our tooltips must be positioned near the links they're attached to. Thus tooltips must also be block-level elements. For compatibility reasons, if you need that your tooltips work as intended also in browsers that don't support CSS3 border properties, then it would be preferable a background image set on the tooltip itself.

We iterate over each link contained within paragraphs and we store first the original value of the title attribute and then we remove it from the element. Then we create our tooltip element and we append it to body, also hiding it.

Now it's time to handle mouse interactions. We'll use the mouseover and mouseout handlers for that purpose. Since we need to track coordinates, we'll pass the event object to the function attached to the mouseover handler, and we'll use the pageX (horizontal axis) and pageY properties to position our tooltips on the screen. Here's the code:

Once the mouse passes on the link, the tooltip is showed. Later, when the mouse leaves the link, the tooltip is hidden with a delay that creates a nice fadeout effect. As you can see, we've used absolute positioning combined with the coordinates taken from the event object. You can see the final result here.

This entry was posted in jquery by Gabriele Romanato. Bookmark the permalink.