Create a customisable jQuery tooltip

Posted 4 years ago by Matt

In the past few years I've come across hundreds of tool tips of every size, colour, with and without animation, persistent, modal... But they all require including separate JavaScript and CSS files, some even so extensive that I had to spend hours learning to customise them.

This is very time consuming and clearly a waste of time so I came up with a simple tooltip, it takes literally seconds to implement and it can be styled just like a normal div in no time.

All it takes to be implemented in the HTML is encapsulating your element between a span containing a class called tooltip with a custom attribute that I called 'desc' (as in description). That's all it is really, so for example if you have a link: <a>Click here</a> and you wanted to add a tooltip to it all it takes is adding the desc attribute like so: <span class="tooltip" desc="this is my tooltip"><a>Click here</a></span>

$(".tooltip").hover(
    function(){
        var content = $(this).attr("desc");
        $(this).prepend("<span class='tooltipContent'>" + content + "</ span>");
    },function () { 
        $(this).find("span:last").remove();
    } 
);

On the first line we tell the program to run the function only when the user hovers with their mouse over the element with the .tooltip class (on an iPad this will be triggered when the user taps on the element).

Next we assign the value of the desc attribute from the hovered element to a variable which we call 'content' and prepend a span (class tooltipContent) with this value to the hovered element and this will be the container of our tooltip.

The following function is triggered when the user hovers out of the element and what it does is remove the previously prepended span so the tooltip disappears.

Now we can easily style and position our tooltip with some basic CSS styles:

.tooltip { position:relative; }
.tooltipContent { position:absolute; top:-30px; left:18px; z-index:99; width:200px; height:auto; padding:10px; color:#fff; background- color:rgba(0,0,0,0.7); font-size:12px; text-shadow:rgba(0,0,0,1)0px 1px 0px; border-radius:4px; box-shadow:rgba(0,0,0,0.5)2px 2px 8px; }

First we set the tooltip position to relative just so we can easily position the content relative to the hovered element. Then in the following line we just style the tooltip, set its position, background color and so on.

This can be used with pretty much any element on the DOM, I usually use it on forms when I need to explain something further, I'd add an question mark-like icon like this:

<span class="tooltip" desc="Enter your first name"><img src="image.png"></span>

That's all it takes to have a simple tooltip on any element on your page.

Quick links