clueTip: A jQuery Tooltip Plugin

# ‹‹ homeclueTip: A jQuery Tooltip Plugin

Now ThemeRoller Ready (as of clueTip 1.1).

# Overview

The clueTip plugin allows you to easily show a fancy tooltip when the user's mouse hovers over (or, optionally, clicks on) any element you designate in your script. If the element includes a `title` attribute, its text becomes the heading of the clueTip.

If you like this plugin and you're feeling generous, perhaps you'd also like to visit my amazon.com wish list?

# Quick Start Guide

Showing the most basic clueTip can be achieved in two easy steps.
Add HTML markup to your page for elements that you want to invoke a clueTip. By default, the clueTip plugin will use the `rel` attribute to load contents into the tooltip body via AHAH.

      <!-- use ajax/ahah to pull content from fragment.html: -->
      <p><a class="tips" href="fragment.html" rel="fragment.html">show me the cluetip!</a></p>

      <!-- use title attribute for clueTip contents, but don't include anything in the clueTip's heading -->
      <p><a id="houdini" href="houdini.html" title="|Houdini was an escape artist.|He was also adept at prestidigitation.">Houdini</a></p>

Include the jQuery core file and the clueTip plugin in the `<head>` of your document. You may optionally include the hoverIntent plugin as well. After these scripts are referenced, you can reference a custom script file to invoke your clueTips (preferred) or enter the script directly in the `<head>` (shown below). You should also include the clueTip stylesheet (jquery.cluetip.css) after the scripts.

    <script src="jquery.js" type="text/javascript"></script>
    <script src="jquery.hoverIntent.js" type="text/javascript"></script> <!-- optional -->
    <script src="jquery.cluetip.js" type="text/javascript"></script>

    <script type="text/javascript">
    $(document).ready(function() {
      $('a.tips').cluetip();

      $('#houdini').cluetip({
        splitTitle: '|', // use the invoking element's title attribute to populate the clueTip...
                         // ...and split the contents into separate divs where there is a "|"
        showTitle: false // hide the clueTip's heading
      });
    });
    </script>
    <link rel="stylesheet" href="jquery.cluetip.css" type="text/css" />

You can change the default style and behavior in many ways. See API / Options for details.

# clueTip Plugin Features

- Multiple Content Sources
- Smart Positioning
- Flexible Behavior
- Style Variety

#### Multiple Content Sources

The contents of the clueTip can come from one of these sources:

1. a separate file, via AHAH / AJAX
2. an element on the same page, typically hidden
3. the title attribute, parsed by a user-defined delimiter (if the "splitTitle" option is set). The text before the first delimiter becomes the clueTip title, and the rest of the text parts are placed in `<div class="split-body"></div>` elements and appended to the clueTip body
4. the return value of a function referenced in the first argument of `.cluetip()`.

#### Smart Positioning

The clueTip Plugin has 4 positioning modes, which you can change via the "positionBy" option.

1. `positionBy: 'auto'` (default)
   - places the tooltip just to the right of the invoking element, but...
   - if there is not enough room for the tooltip to be fully visible between the right edge of the invoking element and the right edge of the browser window, switches from the right side to the left side, but...
   - if the invoking element is too close to the bottom edge of the browser window, adjusts the tooltip upwards until the whole tooltip is visible, but...
   - if the tooltip is taller than the window (i.e. the viewable area), adjusts the tooltip back down until the tooltip's top is at the top edge of the browser window, but...
   - position if the invoking element is so wide that the tooltip can't completely fit to the left or the right of it, places the tooltip to the right or left of the mouse, but...
   - if the tooltip itself can't fit to the right or left of the mouse position, places the tooltip below the mouse position (centered horizontal if enough room), but...
   - if (a) there isn't enough room below without being cut off, and (b) there is enough room between the top of the viewable area and the mouse, puts the tooltip above the mouse position
2. `positionBy: 'mouse'`
   - places the tooltip to the right of the mouse position, but...
   - if there is not enough room to the right, places the tooltip to the left of the mouse position, but...
   - if the tooltip itself can't fit to the right or left of the mouse position, places the tooltip below the mouse position (centered horizontally if enough room), but...
   - if (a) there isn't enough room below without being cut off, and (b) there is enough room between the top of the viewable area and the mouse, puts the tooltip above the mouse position
3. `positionBy: 'bottomTop'`
   - places the tooltip below the mouse position (centered horizontally if enough room), but...
   - if (a) there isn't enough room below without being cut off, and (b) there is enough room between the top of the viewable area and the mouse, puts the tooltip above the mouse position
4. `positionBy: 'fixed'`
   - places the tooltip in the same location relative to the invoking element, regardless of where it appears on the page.
   - the fixed position can be adjusted by modifying the number of pixels in the `topOffset` and `leftOffset` options

#### Flexible Behavior

1. The clueTip takes advantage of Brian Cherne's hoverIntent plugin if it's available. (Just include it in a `<script>` tag if you want the clueTip to use it.)
2. It can be activated on hover or on click.
3. It can fade in, slide down, etc.
4. It can close when the invoking element is moused out or when the tooltip is moused out or when the user clicks a "close" link.
5. It can cache the results of ajax requests—or not.
6. It can be turned off

#### Variety of Styles

The clueTip Plugin comes with three themes: default, jTip, and rounded corners. Additional themes can be created by following the naming patterns in the stylesheet, jquery.cluetip.css. To apply one of the alternative themes, just indicate it in the `cluetipClass` option as `'jtip'` or `'rounded'`.

The "loading" image comes from this rule in the stylesheet:

    #cluetip-waitimage {
          width: 43px;
          height: 11px;
          position: absolute;
          background-image: url(wait.gif);
        }

It can be turned off with the following option: `waitImage: false`

Other options that affect the visual appearance include `hoverClass`, `arrows`, `dropShadow`, and `dropShadowSteps`. Please see API / Options for more information.

# clueTip Plugin API / Options

The clueTip Plugin API provides two methods, with many options. It also provides a custom event for closing the tooltip programmatically

`$.cluetip.setup(options)`
  Global defaults for clueTips. Will apply to all calls to the clueTip plugin.

    {
              insertionType:    'appendTo', // how the clueTip is inserted into the DOM
                                            // possible values: 'appendTo', 'prependTo', 'insertBefore', 'insertAfter'
              insertionElement: 'body'      // where in the DOM the clueTip is to be inserted
            }

`cluetip(options)`
  Displays a highly customizable tooltip via ajax (default) or local content or the title attribute of the invoking element

    $.fn.cluetip.defaults = {  // default options; override as needed
        multiple:         false,    // Allow a new tooltip to be created for each .cluetip() call
        width:            275,      // The width of the clueTip
        height:           'auto',   // The height of the clueTip. more info below [1]
        cluezIndex:       97,       // Sets the z-index style property of the clueTip
        positionBy:       'auto',   // Sets the type of positioning. more info below [2]
        topOffset:        15,       // Number of px to offset clueTip from top of invoking element. more info below [3]
        leftOffset:       15,       // Number of px to offset clueTip from left of invoking element. more info below [4]
        local:            false,    // Whether to use content from the same page for the clueTip's body
                                    // (treats the attribute used for accessing the tip as a jQuery selector,
                                    // but only selects the first element if the selector matches more than one). more info below [5]
        hideLocal:        true,     // If local option is set to true, this determines whether local content
                                    //  to be shown in clueTip should be hidden at its original location
        localPrefix:      null,       // string to be prepended to the tip attribute if local is true
        localIdSuffix:    null,     // string to be appended to the cluetip content element's id if local is true
        attribute:        'rel',    // the attribute to be used for fetching the clueTip's body content
        titleAttribute:   'title',  // the attribute to be used for fetching the clueTip's title
        splitTitle:       '',       // A character used to split the title attribute into the clueTip title and divs
                                    // within the clueTip body. more info below [6]
        escapeTitle:      false,    // whether to html escape the title attribute
        showTitle:        true,     // show title bar of the clueTip, even if title attribute not set
        cluetipClass:     'default',// class added to outermost clueTip div in the form of 'cluetip-' + clueTipClass. more info below [7]
        hoverClass:       '',       // class applied to the invoking element onmouseover and removed onmouseout
        waitImage:        true,     // whether to show a "loading" img, which is set in jquery.cluetip.css
        cursor:           'help',
        arrows:           false,    // if true, displays arrow on appropriate side of clueTip. more info below [8]
        dropShadow:       true,     // set to false if you don't want the drop-shadow effect on the clueTip
        dropShadowSteps:  6,        // adjusts the size of the drop shadow
        sticky:           false,    // keep visible until manually closed
        mouseOutClose:    false,    // close when clueTip is moused out: false, 'cluetip', 'link', 'both'
        delayedClose:     50,        // close clueTip on a timed delay
        activation:       'hover',  // set to 'click' to force user to click to show clueTip
        clickThrough:     true,    // if true, and activation is not 'click', then clicking on a clueTipped link will take user to
                                    // the link's href, even if href and tipAttribute are equal
        tracking:         false,    // if true, clueTip will track mouse movement (experimental)
        closePosition:    'top',    // location of close text for sticky cluetips; can be 'top' or 'bottom' or 'title'
        closeText:        'Close',  // text (or HTML) to to be clicked to close sticky clueTips
        truncate:         0,        // number of characters to truncate clueTip's contents. if 0, no truncation occurs

        // effect and speed for opening clueTips
        fx: {
                          open:       'show', // can be 'show' or 'slideDown' or 'fadeIn'
                          openSpeed:  ''
        },

        // settings for when hoverIntent plugin is used
        hoverIntent: {
                          sensitivity:  3,
                          interval:     50,
                          timeout:      0
        },

        // function to run just before clueTip is shown.
        // If the function returns false, the clueTip is NOT shown
        // It can take a single argument: the event object
        // Inside the function, this refers to the element that invoked the clueTip
        onActivate:       function(event) {return true;},

        // function to run just after clueTip is shown. It can take two arguments:
        // the first is a jQuery object representing the clueTip element;
        // the second a jQuery object represeting the clueTip inner div.
        // Inside the function, this refers to the element that invoked the clueTip
        onShow:           function(ct, ci){},

        // function to run just after clueTip is hidden. It can take two arguments:
        // the first is a jQuery object representing the clueTip element;
        // the second a jQuery object represeting the clueTip inner div.
        // Inside the function, this refers to the element that invoked the clueTip
        onHide:           function(ct, ci){},

        // whether to cache results of ajax request to avoid unnecessary hits to server
        ajaxCache:        true,

        // process data retrieved via xhr before it's displayed
        ajaxProcess:      function(data) {
                            data = data.replace(/<(script|style|title)[^<]+<\/(script|style|title)>/gm, '').replace(/<(link|meta)[^>]+>/g,'');
                            return data;
        },
        // can pass in standard $.ajax() parameters. Callback functions, such as beforeSend,
        // will be queued first within the default callbacks.
        ajaxSettings: {
          // error: function(ct, ci) { /* override default error callback */ },
          // beforeSend: function(ct, ci) { /* called first within default beforeSend callback */ },
          dataType: 'html'
        }
      };

`$(document).trigger('hideCluetip')`
  Hides any currently visible cluetip.

    // example for how you might do this with touch devices
    $('body').bind('touchstart', function(event) {
     event = event.originalEvent;
     var tgt = event.touches[0] && event.touches[0].target,
         $tgt = $(tgt);

     if (tgt.nodeName !== 'A' && !$tgt.closest('div.cluetip').length ) {
       $(document).trigger('hideCluetip');
     }
    });

1. height: Setting a specific height also sets <div id="cluetip-outer"> to "overflow:auto"
2. positionBy: Available options are 'auto', 'mouse', 'bottomTop', 'topBottom', fixed'. Change to 'mouse' if you want to override positioning by element and position the clueTip based on where the mouse is instead. Change to 'bottomTop' if you want positioning to begin below the mouse when there is room or above if not (and 'topBottom' for vice versa) — rather than right or left of the elemnent and flush with element's top. Change to 'fixed' if you want the clueTip to appear in exactly the same location relative to the linked element no matter where it appears on the page. Use 'fixed' at your own risk.
3. topOffset:For all but positionBy: 'fixed', the number will be added to the clueTip's "top" value if the clueTip appears below the invoking element and subtracted from it if the clueTip appears above. For positionBy "fixed", the number will always be added to the "top" value, offsetting the clueTip from the top of the invoking element.
4. leftOffset: For all but positionBy: 'fixed', the number will be added to clueTip's "left" value if the clueTip appears to the right of the invoking element and subtracted if the clueTip appears to the left. For positionBy "fixed", the number will always be added to the "left" value of the clueTip, offsetting it from the right side of the invoking element.
5. local: for example, using the default tip attribute, "rel", you could have a link — <a href="somewhere.htm" rel=".someClass"> — that would show the contents of the first element in the DOM that has a class of "someClass."
6. splitTitle: if used, the clueTip will be populated only by the title attribute
7. cluetipClass: this is also used for a "directional" class on the same div, depending on where the clueTip is in relation to the invoking element. The class appears in the form of 'cluetip-' + direction + cluetipClass. this allows you to create your own clueTip theme in a separate CSS file or use one of the three pre-packaged themes: default, jtip, or rounded.
8. arrows: UPDATE: this option displays a div containing an arrow background image. Arrow images are set using the background-image property in the CSS. The direction of the arrow changes depending on which side of the invoking element the clueTip appears. The arrows option sets the background-position of the cluetip div so that the arrow will accurately point to the invoking element, regardless of where it appears in relation to it.

# Frequently Asked Questions

How is clueTip licensed?

  The clueTip plugin is licensed the same way as the jQuery core file: under a dual MIT and GPL license. Users of the plugin can choose whichever license suits them. The top of the jquery.cluetip.js file has this notice:

  Dual licensed under the MIT and GPL licenses:
  * http://www.opensource.org/licenses/mit-license.php
  * http://www.gnu.org/licenses/gpl.html

What versions of jQuery is the clueTip Plugin compatible with?
  As of clueTip version 1.06, the plugin is compatible with version 1.3.2 or later. Previous clueTip versions are compatible with jQuery 1.2.6, though 1.3.2 or later is recommended.
Does the clueTip Plugin have any dependencies on other plugins?
  No. However, optional plugins that can be used in conjunction with the clueTip plugin include hoverIntent and bgIframe.
How do I get clueTip to work on elements that have been inserted via ajax after the page loads?
  You can call the `.cluetip()` method on those elements from within the ajax method's callback function. For example:

      $.get('/path/to/file', function(html) {
        var newHtml = $(html);
        newHtml.appendTo('#some-elememnt');
        newHtml.find('a').cluetip();
      });

How do I get clueTip to show ajaxed content that has changed on the server?
  There are a number of options available for working with dynamic content. By default, the `ajaxCache` function is set to `true`. This reduces the number of http requests made to the server. However, it doesn't account for possible changes to the ajaxed data. If the contents of a particular clueTip will be updated on the server between invocations, you may want to set `ajaxCache: false`.
How do I programmatically close (hide) a clueTip?
  If you want to trigger a clueTip to close, based on some other interaction, you can use the following code: `$(document).trigger('hideCluetip');`
Why don't the styles that I've applied to my local content carry over once they're inside a clueTip?
  When using an element on the same page to populate the clueTip's content, the plugin clones that element. Because of potential problems caused by duplicate IDs within a page, the plugin also, by default, adds a suffix to the ID of the cloned element. If you have tied styles to the original ID, they won't be carried over. You can either give the `localIdSuffix` an empty string ( '' ) for its value or add the ID to your stylesheet rule.
Why don't form elements within a clueTip update when I tell them to?
  If you attempt to update an element based on its ID,
How do I add a delay before showing or closing the clueTip?
  While the clueTip plugin itself doesn't have a mechanism for delaying responses, it can take advantage of the optional hoverIntent plugin. To delay the showing of a clueTip, use the `interval` property of the `hoverIntent` option; to delay its hiding, use the `timeout` property. Both properties are measured in milliseconds. For example, the following sets both the show and the hide delays to 750 milliseconds (3/4 second):

      $('a').cluetip({
        hoverIntent: {
          sensitivity:  1,
          interval:     750,
          timeout:      750
        }
      });

  See hoverIntent plugin's documentation for details.
Why are the clueTips hidden behind my Flash elements?

  This is a common problem when trying to layer a DOM element over a Flash object. To avoid it, you need to set <param name="wmode" value="transparent" /> inside the <object></object> tags and/or wmode="transparent" as an attribute of the <embed /> tag. For example, your HTML might look like this:

      <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
        codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab"
        width="500" height="300">
        <param name="movie" value="test.swf" />
        <param name="quality" value="high" />
        <param name="wmode" value="transparent" />

        <embed src="test.swf" quality="high" wmode="transparent"
          pluginspage="http://www.macromedia.com/go/getflashplayer"
          type="application/x-shockwave-flash" width="500" height="300" />
      </object>

# clueTip Plugin Credits

- Originally inspired by Cody Lindley's jTip
- Huge thanks to Jonathan Chaffer, Glen Lipka, Torben Schreiter, Dan G. Switzer, Jörn Zaefferer, Shelane Enos, Hector Santos, and the many others who helped report and fix bugs and suggest features.

# Download

The plugin is available on Github, where it is updated more frequently with incremental improvements and bug fixes: clueTip on Github

# Bug Reports

If you discover a bug in the clueTip plugin, please report the bug here.