18 Feb, 2009

Published at 10:56PM

Tagged with ballpark, design, javascript, jquery, and plugin

This post has 0 comments

Simple tooltip plugin for jQuery

In Ballpark I recently swapped out some link text for icons. That’s all well and good, but sometimes icons aren’t always accurate in their meaning. Of course I had title attributes, but that 0.5 seconds it takes for that to show up could potentially be too late. So I wrote a jQuery plugin to show fancy tooltips based on the title attribute. Here’s the gist of it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
(function($) {
  $.fn.tooltip = function(options) {
    var options = $.extend({
      xOffset: 30,
      yOffset: 7,
      follow: false
    }, options)

    return this.each(function() {
      $(this).hover(function(e) {

        // prevent duplicate "hovers"
        this._title = this.title
        this.title = ''

        $('body').append('<p id="tooltip">' + this._title + '</p>')
        $('#tooltip').
          css('top', (e.pageY - options.yOffset) + 'px').
          css('left', (e.pageX + options.xOffset) + 'px').
          fadeIn('fast')
      }, function() {
        this.title = this._title
        $('#tooltip').remove()
      })

      // supports the option to follow the
      // tooltip wherever the cursor goes
      if (options.follow) {
        $(this).mousemove(function(e) {
          $('#tooltip').
            css('top', (e.pageY - options.yOffset) + 'px').
            css('left', (e.pageX + options.xOffset) + 'px')
        })
      }
    })
  }
})(jQuery)

To use it, just call .tooltip() on the selected elements, like so:

1
2
3
$(document).ready(function() {
  $('span.options a').tooltip()
})

You can specify the X and Y offsets in the options, but the defaults are pretty good. One thing you may have an opinion on is whether or not the tooltip should follow along with the cursor. So I’ve made that option available, too:

1
$('span.options a').tooltip({ follow: true })

Anyway, it’s a pretty simple plugin. All of the other options that I found did way more than I needed (ajax loading and such), so I thought it was worth documenting this one.

Oh, and just style the #tooltip element in your CSS to make it look pretty :-)

Comments

Do you have something to say about this post?
Retype the image to the right Spam Hint: Are You Human? Textile Formatting Tips

or

Ryan Heath | Site Management A Ruby on Rails production.

This site is a Formed Function. Formed Function LLC | @formedfunction | Get in Touch