jQuery Tools / Tooltip - Tooltips done right
The Story
Tooltips are one of the most important JavaScript widgets on the web. Although important, they also happen to be a very badly misunderstood and poorly implemented component. This tool corrects the situation. You'll get a professional piece of sofware that is easy to understand and use. Here are the highlights of this tool:
- Typically, you will need a single JavaScript one-liner to get started.
- Appearance and dimensions can be tweaked with CSS.
- The tooltip can contain any HTML such as images, tables and forms or it will generate tooltips from each element's title attribute as in the demo above.
- You have full control over the positioning.
- There is an improved event management system for controlling when the tooltip will be shown or hidden.
- You can move the cursor on top of the tooltip so you can use links or form inside it
- You can control the tooltip timings before and after your mouse moves over the trigger element.
- Pluggable effects. Tooltip comes with two build-in effects: toggle, and fade and one separate effect: slide and you can easily build your own effects.
- A dynamic plugin will dynamically change the tooltip's position so that it always stays in the viewport.
This tool uses a simple and natural syntax and has an advanced programming API. You can extend it with callback methods or with your own plugins. This tool has a similar structure and feel as the other tools. Learn to use this tool and you will know how to use the rest.
This tool is a mature project and is actively maintained. The source code is clean, professional and easy to follow. It passes Douglas Crockford's JavaScript Verifier and it it doesn't assign any global variables. Active forums keep this tool alive and you can expect to see new releases coming out in the future.
The available tooltip functionality and configuration variables are minimal because tooltip functionality is inherently simple. If you want to do complex things, you can do them with "normal" jQuery programming. You often see bloated tooltip solutions because they contain functionality that should not be there. For example, if for some weird reason you want to use AJAX requests with tooltips, you can do them with jQuery. AJAX functionality should not be mixed in with the tooltip code.
Usage
We believe that the best way to learn is through demos. The following demos are fully documented and a standalone page is provided to get tooltip working on your site. It's really important to study the first demo "Basics of using the tooltip", because it teaches you the basics of using the library.
- Basics of using the tooltip
- Using any HTML inside the tooltip
- Imitating browsers default tooltip
- Using tooltips in form fields
- Using tooltips in tables or lists
- Custom tooltip effect
- Dynamic positioning of the tooltip
tooltip Graphics
You can use our graphics as the basis for your design. You can freely change the design as you see fit. Click the image on the right to download a zip file. Before using the graphics, you should consult the User's Guide on how graphics can be used when designing the look and feel of the tools.
Here are a few examples of what is included in the zip file:
Configuration
There are many other ways of using this tool than the demos provided above. The generic form of initializing tooltips is the following:
// selectors
$("<trigger_selector>").tooltip({
/* tooltip configuration goes here */
// one configuration property
position: "bottom left",
// another property
opacity: 0.7,
// ... the rest of the configuration properties
});
You select one or more elements with a jQuery selector that will trigger the tooltip(s). The tool looks for the element that is placed next to the tooltip to be the tooltip. The return value is a jQuery object associated with the selection. Here is a full list of available configuration options:
| property | default | description |
|---|---|---|
| api | false |
When this tool is initialized (constructed), the return value is a jQuery object associated with the selector. By setting this property to true, the return value is this tool's JavaScript API instead. If the selector returns multiple elements, the API of the last element will be returned. Read more about accessing the tool API for more information. |
| cancelDefault | true |
Since 1.1.0. When tooltip content is fetched from the title attribute of the trigger element this property cancels the default tooltip behaviour executed by the browser. This is achieved by simply removing the title attribute from the trigger.
You can still retrieve / modify the title value by calling jQuery's data("title") method for the trigger. |
| effect | 'toggle' |
Specifies how the tooltip is shown and hidden. There are two built-in effects that can be used as values:
There is also a slide effect which is not included in the tool itself. You can build your own effects too. |
| delay | 30 |
Specifies how long the tooltip remains visible after the mouse leaves the trigger. This is necessary if the tootip has interactive content and the user will need time to move to the tootip area. By setting this to 0 the tooltip will disappear as soon as the mouse moves away from the trigger element. |
| events | Object |
A configuration object that specifies when the tooltip will be shown and hidden. You can specify different events for different kinds of elements. Here are the default values for this property:
You can read more about this topic in the event management chapter. |
| lazy | undefined |
Since 1.1.0. Waits to perform the tooltip initialization until the tooltip is first being used. If you have many tooltip elements on the page, this will make your page load faster. By default this is enabled if you have more than 20 tooltips on the page. You can explicitly enable or disable this feature by setting this to true or false respectively. Note: Currently this feature must be disabled when using it together with the dynamic plugin. |
| offset | [0, 0] |
Fine tunes the tooltip position specified with the position property. See the positioning details for more information. |
| opacity | 1 |
The transparency of the tooltip. For example, 0 means invisible, 1 means no transparency (fully visible) and 0.4 means that 40% of the tooltip is shown. If your tooltip uses a CSS background image, you can set the transparency of the image if it has been saved in the PNG24 graphics format. Remember that Internet Explorer 6 does not natively support PNG transparency. |
| position | 'top center' |
Specifies the position of the tooltip. See the positioning details for more information. The old format: ['top', 'center'] is deprecated and will be removed in the future. |
| predelay | 0 |
Since 1.1.0. Specifies the delay (in milliseconds) before the tooltip is shown. By default there is no delay. |
| relative | false |
Since 1.1.1. by default the tooltip position is now determined relative to the document (by using the offset() method of jQuery). By enabling this property the tooltip position is determined relative to the parent element |
| tip | |
This jQuery selector selects the tooltip element being used. When tooltip content is fetched from the title attribute of the trigger then this property is required. If this selector returns a single tooltip element then this same tooltip is used for each trigger. If this property is not given or this selector returns multiple elements, it is assumed that the element that is placed next to the trigger will function as the tooltip. In this case this value is used as a filter for jQuery's nextAll method which will scan for a tip element after the trigger element and return the first one found. If the scan fails to return any element then an additional scan is made starting from the trigger's parent element. Note that if this is the only configuration variable you are using, then you can give the whole configuration as a string which is the selector for the tip element. |
| onBeforeShow | |
This callback function is triggered before the tooltip is shown. Returning false in the callback prevents the tooltip from appearing. The callback function receives one argument specifying the tooltip position to be used. This is an object with values {top: integer, left: integer} |
| onShow | |
This callback function is triggered after the tooltip is shown. |
| onBeforeHide | |
This callback function is triggered before the tooltip is hidden. Returning false in the callback prevents it from hiding. |
| onHide | |
This callback function is triggered when the tooltip is hidden. |
Tooltip positioning
The tooltip position is specified with two different configuration properties: position and offset. Both are JavaScript arrays with two values. The position property specifies the position in relation to the trigger element. For example, a value of 'bottom center' will place the tooltip on the bottom edge of the trigger, centered horizontally. The following image illustrates the "slots" that you can use:
The offset property fine tunes the tooltip position specified with the position property. For example, the value [10, -20] moves the tooltip position 10px downwards and 20px to the left. The first value modifies the vertical positioning from the top edge of the tooltip and the second value modifies the horizontal positioning from the left edge of the tooltip. Positive values move the tooltip downward and to the right, while negative values move the tooltip upward and to the left.
Using callback functions
Inside any callback function, the this variable is a pointer to the tooltip scripting API. Here is an example of an onShow callback function that fades out the trigger element when the tooltip is shown:
$("label").tooltip({
// change trigger opacity slowly to 0.8
onShow: function() {
this.getTrigger().fadeTo("slow", 0.8);
}
});
See the Using Callback Functions section of the User's Guide for a more detailed dscription about this important topic.
Event management
jQuery Tooltip allows you to fully control when the tooltip will be shown or hidden. You can specify different events for different types of elements. You can control this behaviour with the events configuration variable which has following values by default.
events: {
def: "mouseover,mouseout", // default show/hide events for an element
input: "focus,blur", // for all input elements
widget: "focus mouseover,blur mouseout", // select, checkbox, radio, button
tooltip: "mouseover,mouseout" // the tooltip element
}
This specifies opening and closing events for various types of trigger elements. def accepts a value mouseover,mouseout which means that by default the tooltip is shown when the mouse moves over the trigger and hides when the mouse moves away from the trigger. For input elements (text, textarea, password) the tooltip shows when the input is focused and hides when focus moves out of the field.
widget is a convenience type which means select, checkbox, radio and button elements. For them the tooltip is shown on both focus and mouseover events and hidden on both blur and mouseout events. This is just a convenience because these elements usually need same kind of tooltip behaviour.
since 1.1.2 you can also customize the events for the tooltip element. By default the tooltip stays visible when the mouse is moved over it and it is hidden upon mouseout. If you don't want to close the tooltip upon mouseout, you can simply specify: tooltip: "mouseover". This gives you the possibility of closing the tooltip programmatically. This has been done on the login/signup boxes on the main navigation bar of this website.
If you want to customize these events you can follow the example below:
$("label").tooltip({
events: {
input: 'click, blur',
checkbox: 'mouseover click, mouseout',
date: 'click, blur'
}
});
This will override the events for every input element. We have also defined customized events for checkbox field. The tool checks for the trigger element's type attribute to lookup appropriate events from the configuration.
The format of the value is: showEvent11 showEvent2 ... showEventN,closeEvent1 closeEvent2 ... closeEventN. You first supply all showing events separated with spaces followed by a comma (,) followed by all close events separated with spaces. A list of available events can be found here. Look for the "Event Helpers" section.
Nothing stops you from adding special types for your elements just by defining a type attribute. Here we use a date type that was added to the HTML5 specification and the corresponding element on the page is defined like this:
<input type="date" name="birthDate" />
Here is a demo that shows you the various event types in action.
Scripting API
This tool has a useful API for scripters. A lot of effort has been put into it so that you can enrich the tooltip experience. You can get a handle to the API in numerous ways as described in the User's Manual. Here is an example of how to access the API:
/*
get handle to the third tooltip on the page
(must have been constructed before the call)
*/
var api = $("a.withTooltip").tooltip(2)
// show the tooltip
api.show();
Here is a list of all API methods:
| method | return value | description / example |
|---|---|---|
| show() | API |
Shows the tooltip. |
| hide() | API |
Hides the tooltip. |
| isShown() | boolean |
Returns true if the tooltip is visible. |
| getTip() | jQuery |
Returns the tooltip as a jQuery object. |
| getTrigger() | jQuery |
Returns the triggering element as a jQuery object. |
| getConf() | Object |
Returns the tooltip configuration. |
| onBeforeShow(fn) | API |
Registers a new callback function that is triggered before the tooltip is shown. The callback is given as the argument. Returning false in the callback prevents the tooltip from showing. You can assign multiple onBeforeShow listeners with this command. See using callbacks for more information.
The first argument for the callback function is the Event object and the second is the tooltip position to be used. This is an object with values {top: integer, left: integer}. |
| onShow(fn) | API |
Registers a new callback function that is triggered after the tooltip is shown. The callback is given as the argument. You can assign multiple onClick listeners with this command. |
| onBeforeHide(fn) | API |
Registers a new callback function that is triggered before the tooltip is hidden. The callback is given as the argument. Returning false in the callback prevents the tooltip from hiding. You can assign multiple onBeforeHide listeners with this command. |
| onHide(fn) | API |
Registers a new callback function that is triggered after the tooltip is hidden. The callback is given as the argument. You can assign multiple onHide listeners with this command. |
| bind(names, fn) | API |
Register one or more callbacks to be triggered. See using callbacks for more information. |
| unbind(names) | API |
Removes callback functions from the tool See using callbacks for more information. |
Built-in effect: fade
The built-in effect "fade" has its own set of configuration options as follows:
| property | default | description |
|---|---|---|
| fadeInSpeed | 400 | The fade-in speed when the tooltip is shown, in milliseconds |
| fadeOutSpeed | 200 | The fade-out speed when the tooltip is hidden, in milliseconds |
Making custom effects
If you want to make custom effects, you'll use the $.tools.tooltip.addEffect method. This method is "static", meaning that you don't have to have the tooltip API (or instance) already loaded. You can add effects before any tooltips are constructed.
This method accepts three arguments. The first argument is the effect name, the second argument is the function that performs the required functionality for showing the tooltip and the third argument is a function that hides the tooltip. You can use this method to modify existing effects or add new ones. Here is an example:
// adds an effect called "myEffect" to tooltip
$.tools.tooltip.addEffect("myEffect",
// show function
function(done) {
// 'this' variable is a reference to the tooltip API
var conf = this.getConf(), tip = this.getTip();
// peform your effect. for example:
tip.css({opacity: 1, width: '+=50'});
// after you have finished you must do
done.call();
},
// hide function
function(done) {
// peform your effect. for example:
this.getTip().animate({opacity: 0, width: '-=50'}, done);
}
);
As you can see inside the functions the this variable is a pointer to the scripting API. Which gives you access to various parts of the tooltip elements. The functions are fed with one argument which is a reference to a function that must be called after you have performed your effect. The reason for this is that many times those effects perform animations that have a certain duration. We must know when these animations are finished so that the onShow and onHide events are really called after the tooltip is completely shown or hidden.
Note that if you are using jQuery's animate method the "done" function can simply be given to this method as the last argument. jQuery will take care of it after the animation finishes.
The default effect
Effects are actually quite easy to implement. Here are the functions for the default show/hide effect:
// show function
function(done) {
this.getTip().show();
done.call();
},
// hide function
function(done) {
this.getTip().hide();
done.call();
}
Look at tooltip's source code for more examples of the effects. The basic idea is to use your jQuery skills together with the API methods. Here you can see a demo about the custom sliding effect.
Effects and Plugins
Effect: Slide
The slide effect makes your tooltips slide. Move your mouse over the download button below and you can see it in action:
Download nowHere you can see the JavaScript setup for above setup:
$(document).ready(function() {
// enable tooltip for "download" element. use the "slide" effect
$("#download_now").tooltip({ effect: 'slide'});
});
Configuration options
Here is a full list of available configuration options for this effect. These options are added to the default configuration options.
| property | default | description |
|---|---|---|
| bounce | false |
Since 1.1.0. By default, when the tooltip slides away the sliding continues in the same direction as when the tooltip was shown. By setting this to true the tooltip slides back to its original position. |
| direction | up |
Since 1.1.0. specifies the sliding direction. Valid values are up, down, left and right. |
| slideOffset | 10 | Specifies the position where the tooltip will slide in relation to the trigger element. A positive value means farther upwards and a negative value will cause it to slide farther downwards. |
| slideInSpeed | 200 | The sliding speed when the tooltip is shown, in milliseconds |
| slideOutSpeed | 200 | The sliding speed when the tooltip is hidden, in milliseconds |
| slideFade | !$.browser.msie | Specifies whether sliding is combined with fade-in/fade-out effects. By default this effect is enabled for all browsers exept for Internet Explorer. This is because many times the tooltip has a PNG24 background image and IE does not support opacity changes for PNG24 images. If you want to enable fading for all browsers you can simply set this property to true. You can read more about PNG24 images in the User's Manual. |
This effect uses a fading animation from zero to full opacity in all browsers other than Internet Explorer.
Example
An example setup using slide effect with a custom property slideOffset:
$("a.withTooltip").tooltip({
effect: 'slide',
slideOffset: 30
});
Plugin: Dynamic
Below you can see triggers whose tooltip is centered on the top edge of the trigger. Click here to scroll a little lower and see how the tooltips behave now. We are using the dynamic plugin which repositions our tooltips so that they are always visible in the viewport.
If there is no room on the top edge then the tooltip is shown on the bottom edge. The same happens on every edge of the tooltip: top, bottom, left and right. The opposite edge is always used.
Highlights
- Can be used with any effect
- You can use a custom CSS class name for any repositioned edge. This allows you to style the tooltip differently for each edge.
- You can change the effect and any other configuration variable dynamically whenever repositioning occurs.
- The tooltip's offset configuration variable is inverted. Higher means lower and further right means further left.
- Small file size: only about 2kb of minified code. uncomparable
Usage
The best way to learn is to study the full documentation for the example above. For the impatient here is the JavaScript setup:
$(document).ready(function() {
// initialize tooltip
$("#dyna img[title]").tooltip({
// use single tooltip element for all tips
tip: '#dynatip',
// tweak the position
offset: [10, 2],
// use "slide" effect
effect: 'slide'
// add dynamic plugin
}).dynamic( {
// customized configuration on bottom edge
bottom: {
// slide downwards
direction: 'down',
// bounce back when closed
bounce: true
}
});
});
Configuration
Here is a full list of available configuration options for this plugin.
| property | default | description |
|---|---|---|
| api | false |
By setting this property to true, the return value for the initialization chain is tooltip's JavaScript API. Read more about accessing the tool API for more information. |
| classNames | 'top right bottom left' |
The CSS class names assigned for the tooltip when repositioning occurs. The names are given as a single string where names for different edges are separated with spaces. Note that you must follow the default pattern for designating different edges if you change the class names. |
| top | undefined |
An object with alternate configuration options that will override the default settings when the tooltip is repositioned on the top edge. For example: {offset: [40, -30], effect: 'toggle', opacity: 0.9}. |
| right | undefined |
Alternate configuration options for the right edge. |
| bottom | undefined |
Alternate configuration options for the bottom edge. |
| left | undefined |
Alternate configuration options for the left edge. |
Note: Currently this plugin cannot be used when the lazy configuration variable is enabled for the tooltip.