Ricodigo's blog

We write delicious code.

Easy Tooltips With jQuery UI

There are tons of fancy tooltips plugins available. However, thanks to the position method of jQuery UI, you may not need any of these (if you’re already using jQuery UI) as I’ve found out while adding tooltips to the next Shapado.

One of the ways to do this it to just add a div that will contain the text of your tooltip, in this case we’ll just give it the class ‘tooltip’.

<p>Show me that cool <a class='special'>tooltip</a>.</p>
<div class='tooltip'>
  <div class=arrow>▲</div>
  <div class=text>This is so cool</div>
</div>

And then add some JS:

$(document).ready(function(){
  $('.special').hover(function(){
  $(this).next('.tooltip').show();
  $(this).next('.tooltip').
    position({at: 'bottom center', of: $(this), my: 'top'})
});

What we’re doing here is that when the user hovers over the link, we show the tooltip div and position it at the bottom of the link using the jQuery UI position method.

$('.special').mouseleave(function(){
  $('.tooltip').hide();
});

And then we just hide it when the mouse leaves the link. You could also set a timer to close it or add a button inside the tooltip to close it manually, this is useful if the tooltip contains some medias such as a youtube video or links.

Now we just add a bit of styling and that’s it!

.tooltip{
  text-align: center;
  color: black;
  display: none;
  position: absolute;
}
.tooltip .text{
  background-color: black;
  color:white;
  margin-top: -15px;
}
.tooltip .arrow {margin-bottom: 8px;margin-top: -5px;}
You can obviously add more or less styling to your liking.
Now show me that cool TOOLTIP!
This is so cool

You can read more about jQuery UI position here

Comments