Lorem ipsum dolor sit amet
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu.
After you download Tooltipster, load jQuery and include Tooltipster's CSS and JavaScript files in your page.
<head> <link rel="stylesheet" type="text/css" href="tooltipster/dist/css/tooltipster.bundle.min.css" /> <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.0.min.js"></script> <script type="text/javascript" src="tooltipster/dist/js/tooltipster.bundle.min.js"></script> </head>
Compatibility note: jQuery 1.7 is enough except if you need SVG support in IE (then use jQuery 1.10+). Tooltipster does not work at all with jQuery 1.8 in IE9.
Bonus: available on GitHub but also on Npm, Bower and jsDelivr.
Bonus 2: if you need .gz files, running grunt compress will gzip all files within the dist folder.
To spot the elements which will get a tooltip, aka the "origins", we will give them a 'tooltip' class. You may use another class name or even other means of selection, your choice. After that, we will set the title attribute to whatever we'd like our tooltip to say. Here are a couple examples:
// Putting a tooltip on an image: <img src="my-image.png" class="tooltip" title="This is my image's tooltip message!" /> // Putting a tooltip on some text (span, div or whatever): <span class="tooltip" title="This is my span's tooltip message!">Some text</span>
Note: if you use Twitter's Bootstrap, use another class name because 'tooltip' will create a conflict.
The last thing we have to do is activate Tooltipster. To do this, add the following script right before your closing </head> tag (using whatever selector you like - in this case we're still using the 'tooltip' class):
<head> ... <script> $(document).ready(function() { $('.tooltip').tooltipster(); }); </script> </head>
On top of its default style, Tooltipster is packaged with five themes to choose from.
To use a theme, just include its css file (located in the dist/css/plugins/tooltipster/sideTip/themes folder) in your page and specify its name in Tooltipster's options:
$('.tooltip').tooltipster({ theme: 'tooltipster-noir' });
To bring your own modifications to the style of your tooltips, a custom themes section awaits you below.
Note: "sideTip" is the name of the plugin used by default by Tooltipster. We'll see about plugins later.
Tooltipster allows you to use any HTML markup inside your tooltips. It means that you can insert things like images and text formatting tags.
Instead of a title attribute, use a data-tooltip-content attribute to provide a selector that corresponds to the HTML element of your page that should be used as content. This is your HTML:
<span class="tooltip" data-tooltip-content="#tooltip_content">This span has a tooltip with HTML when you hover over it!</span> <div class="tooltip_templates"> <span id="tooltip_content"> <img src="myimage.png" /> <strong>This is the content of my tooltip!</strong> </span> </div>
In your CSS file, add .tooltip_templates { display: none; } so that the content does not get displayed outside of the tooltip.
Important: if you have two tooltips that have the same data-tooltip-content attribute (that is to say, want to both use the same HTML element), please set the contentCloning option to true when you initialize your tooltips:
$('.tooltip').tooltipster({ contentCloning: true });
Note: there are alternative ways of setting HTML content in the tooltip, discussed in this section.
Tooltipster's features may be extended through the use of plugins. They may add new styles, new options, new methods, new behaviors, etc.
Some popular plugins for Tooltipster are:
sideTip Shipped with Tooltipster and used by default
SVG Shipped with Tooltipster, adds SVG support, not enabled by default (see the SVG section)
follower Lets the tooltip follow the cursor. Available here
scrollableTip Makes the tooltip scrollable when it gets too big. Available here
discovery Creates groups of tooltips for faster display. Demonstrated in the Grouped tooltips section and available here
selectableText Makes a tooltip appear when you select / highlight some text. Available here
For more information about plugins, read our plugins section.
Tooltipster's options give you a wide range of variables to tweak your tooltip to your heart's content. Here's how you declare options:
$('.tooltip').tooltipster({ animation: 'fade', delay: 200, theme: 'tooltipster-punk', trigger: 'click' });
And here is the full list of available options:
Option name | Accepted values | Description |
animation |
'fade', 'grow', 'swing', 'slide', 'fall' |
Determines how the tooltip will animate in and out. In addition to the built-in transitions, you may also create custom transitions in your CSS files. In IE9 and lower, all animations default to a JavaScript generated, fade animation. Default: 'fade' |
animationDuration |
integer, integer[] |
Sets the duration of the animation, in milliseconds. If you wish to provide different durations for the opening and closing animations, provide an array of two different values. Default: 350 |
arrow |
boolean | Add a "speech bubble" arrow to the tooltip. Default: true |
content |
string, jQuery object, any |
If set, this will override the content of the tooltip. If you provide something else than a string or jQuery-wrapped HTML element, you will need to use the 'functionFormat' option to format your content for display. Default: null |
contentAsHTML |
boolean | If the content of the tooltip is provided as a string, it is displayed as plain text by default. If this content should actually be interpreted as HTML, set this option to true. Default: false |
contentCloning |
boolean | If you provide a jQuery object to the 'content' option, this sets if it is a clone of this object that should actually be used. Default: false |
debug |
boolean | Tooltipster logs hints and notices into the console when you're doing something you ideally shouldn't be doing. Set to false to disable logging. Default: true |
delay |
integer, integer[] |
Upon mouse interaction, this is the delay before the tooltip starts its opening and closing animations when the 'hover' trigger is used (*). If you wish to specify different delays for opening and closing, you may provide an array of two different values. Default: 300 |
delayTouch |
integer, integer[] |
Upon touch interaction, this is the delay before the tooltip starts its opening and closing animations when the 'hover' trigger is used (*). If you wish to specify different delays for opening and closing, you may provide an array of two different values. Default: [300, 500] |
distance |
integer, integer[] |
The distance between the origin and the tooltip, in pixels. The value may be an integer or an array of integers (in the usual CSS syntax) if you wish to specify a different distance for each side. Default: 6 |
functionInit |
function | A custom function to be fired only once at instantiation. Arguments. Default: none (null) |
functionBefore |
function | A custom function to be fired before the tooltip is opened. This function may prevent the opening if it returns false. Arguments. Default: none (null) |
functionReady |
function | A custom function to be fired when the tooltip and its contents have been added to the DOM. Arguments. Default: none (null) |
functionAfter |
function | A custom function to be fired once the tooltip has been closed and removed from the DOM. Arguments. Default: none (null) |
functionFormat |
function | A custom function that does not modify the content but that can format it for display. It gets the two first usual arguments and also the content as third argument. It must return the value that will be displayed in the tooltip, either a string or a jQuery-wrapped HTML element (see the formatting section). Default: none (null) |
functionPosition |
function | A custom function fired when the tooltip is repositioned. It gives you the ability to slightly or completely modify the position that Tooltipster is about to give to the tooltip. It gets the proposed set of placement values as third argument. The function must return the set of placement values, which you may have edited (see the positioning section). Default: none (null) |
IEmin |
integer | The minimum version of Internet Explorer to run on. Default: 6 |
interactive |
boolean | Give users the possibility to interact with the content of the tooltip. If you want them to be able to make clicks, fill forms or do other interactions inside the tooltip, you have to set this option to true. When the 'hover' close trigger is used, the user has to move the cursor to the tooltip before it starts closing (this lapse of time has its duration set by the 'delay' option). Default: false |
maxWidth |
integer | Set a maximum width for the tooltip. Default: null (no max width) |
minIntersection |
integer | Corresponds to the minimum distance to enforce between the center of the arrow and the edges of the tooltip. Mainly used to create an arrow bigger than those of the default themes. Default: 16 |
minWidth |
integer | Set a minimum width for the tooltip. Default: 0 (auto width) |
multiple |
boolean | Allows you to put several tooltips on a single element (see the multiple section). Default: false |
plugins |
string[] | The names of plugins to be used by Tooltipster. Default: ['sideTip'] |
repositionOnScroll |
boolean | Repositions the tooltip if it goes out of the viewport when the user scrolls the page, in order to keep it visible as long as possible. Default: false |
restoration |
'none', 'previous', 'current' |
Specifies if a TITLE attribute should be restored on the HTML element after a call to the 'destroy' method. This attribute may be omitted, or be restored with the value that existed before Tooltipster was initialized, or be restored with the stringified value of the current content. Note: in case of multiple tooltips on a single element, only the last destroyed tooltip may trigger a restoration. Default: 'none' |
selfDestruction |
boolean | Sets if the tooltip should self-destruct after a few seconds when its origin is removed from the DOM. This prevents memory leaks. Default: true |
side |
string, string[] |
Sets the side of the tooltip. The value may one of the following: 'top', 'bottom', 'left', 'right'. It may also be an array containing one or more of these values. When using an array, the order of values is taken into account as order of fallbacks and the absence of a side disables it (see the sides section). Default: ['top', 'bottom', 'right', 'left'] |
timer |
integer | How long (in ms) the tooltip should live before closing. Default: 0 (disabled) |
theme |
string, string[] |
Set a theme that will override the default tooltip appearance. You may provide an array of strings to apply several themes at once (see the themes section). Default: empty array |
trackerInterval |
integer | Sets how often the tracker should run (see trackOrigin and trackTooltip), in milliseconds. The tracker runs even if trackOrigin and trackTooltip are false to check if the origin has not been removed while the tooltip was open, so you shouldn't set too high or too low values unless you need to. Default: 500 |
trackOrigin |
boolean | Repositions the tooltip if the origin moves or is resized. As this option may have an impact on performance, we suggest you enable it only if you need to. Default: false |
trackTooltip |
boolean | Repositions the tooltip if its size changes. When the size change results from a call to the 'content' method, the tooltip is already repositioned without the need to enable this option. As this option may have an impact on performance, we suggest you enable it only if you need to. See this entry of the FAQ. Default: false |
trigger |
'hover', 'click', 'custom' |
Sets when the tooltip should open and close. 'hover' and 'click' correspond to predefined sets of built-in triggers, while 'custom' lets you create your own, for a completely customized behavior. See the triggers section to learn how to use custom triggers. Default: 'hover' |
triggerClose |
object | When 'trigger' is set to 'custom', all built-in close triggers are disabled by default. This option allows you to reactivate the triggers of your choice to create a customized behavior. Only applies if 'trigger' is set to 'custom'. See the triggers section. |
triggerOpen |
object | Similar to 'triggerClose'. |
updateAnimation |
'fade', 'rotate', 'scale', null |
Plays a subtle animation when the content of the tooltip is updated (if the tooltip is open). You may create custom animations in your CSS files. Set to null to disable the animation. Default: 'rotate' |
viewportAware |
boolean | Tries to place the tooltip in such a way that it will be entirely visible on screen when it's opened. If the tooltip is to be opened while its origin is off screen (using a method call), you may want to set this option to false. Default: true |
zIndex |
integer | Set the z-index of the tooltip. Default: 9999999 |
Almost all user callbacks have the same input signature. It means that functionInit, functionBefore, functionReady, functionAfter, functionFormat, functionPosition and the open and close callbacks all get these two parameters:
// this is valid for the other callback functions too functionInit(instance, helper){ ... }
Small exception: functionFormat and functionPosition get an extra third parameter (documented above).
instance is the Tooltipster object which is calling the callback function and is described in the object-oriented section.
helper is an object that contains variables that you may find useful. For example:
helper.origin is always present, it's the HTML element on which the tooltip is set.
helper.tooltip is present in functionReady and open callbacks, it's the root HTML element of the tooltip. In other callbacks, it is undefined.
helper.event is present in functionBefore and functionAfter callbacks. It's the mouse or touch event that triggered the opening or the closing of the tooltip. When the action was not triggered by a mouse or touch event, this variable is null or undefined.
For advanced use cases, Tooltipster offers a set of methods to manipulate your tooltips. They allow you to create custom triggers, update tooltip content on the fly (whether the tooltip is currently open or not), destroy Tooltipster functionality if needed, reposition tooltips and more.
Instance methods are used to manipulate one tooltip in particular. There are two ways to call them.
1) Through the origin's HTML element: $('#my-tooltip').tooltipster(methodName [, argument1] [, argument2]);
2) Through the tooltip instance, when you have it: instance.methodName([argument1] [, argument2]);
The latter will be discussed in the object-oriented section. Users with simple use cases just need to know that it's the recommended way of calling methods when you are inside functionInit, functionBefore and the like. Here is the list of instance methods:
Method name | Arguments | Description |
close |
callback | Closes the tooltip. When the animation is over, its HTML element is destroyed (definitely removed from the DOM). The `callback` function argument is optional (see its input signature). |
content (getter) |
None | Returns a tooltip's current content. If the selector matches multiple origins, only the value of the first will be returned. |
content (setter) |
content | Updates the tooltip's content. |
destroy |
None | Closes and destroys the tooltip functionality. |
disable |
None | Temporarily disables a tooltip from being able to open. |
elementOrigin |
None | Returns the HTML element which has been tooltipped. |
elementTooltip |
None | Returns the HTML root element of the tooltip if it is open, `null` if it is closed. |
enable |
None | If a tooltip was disabled, restores its previous functionality. |
instance |
None | Returns the instance of Tooltipster associated to the tooltip. If the selector matches multiple origins, only the instance of the first will be returned. |
on, one, off, triggerHandler |
callback | Handle Tooltipster's events on a per-instance basis (see the events section). |
open |
callback | Opens the tooltip. The `callback` function argument is optional (see its input signature) and, if provided, is called when the opening animation has ended. |
option (getter) |
optionName | Returns the value of an option. |
option (setter) |
optionName, optionValue | Sets the value of an option (for advanced users only; we do not provide support on unexpected results). |
reposition |
None | Resizes and repositions the tooltip. |
status |
None | Returns various information about the tooltip, like whether it is open or not. See the status section. |
Example of the first syntax:
// initialize your tooltip as usual: $('#my-tooltip').tooltipster({}); // at some point you may decide to update its content: $('#my-tooltip').tooltipster('content', 'My new content'); // ...and open it: $('#my-tooltip').tooltipster('open'); // NOTE: most methods are actually chainable, as you would expect them to be: $('#my-other-tooltip') .tooltipster({}) .tooltipster('content', 'My new content') .tooltipster('open');
Example of the second syntax:
$('.tooltip').tooltipster({ functionBefore: function(instance, helper) { instance.content('My new content'); } });
Core methods are methods which may affect/handle several tooltips at once. You call them with: $.tooltipster.methodName([argument]);
Method name | Arguments | Description |
instances |
None OR selector OR HTML element |
Returns the instances of Tooltipster of all tooltips set on the element(s) matched by the argument. If there is no argument, then all instances of all tooltips present in the page are returned. |
instancesLatest |
None | Returns the instances of Tooltipster which were generated during the last initializing call. |
on, one, off, triggerHandler |
Handle Tooltipster's events coming from any instances. See the events section. | |
origins |
None OR selector |
Returns an array of all HTML elements in the page which have one or several tooltips initialized. If a selector is passed, the results will be limited to the descendants of the matched elements. |
setDefaults |
options | Changes the default options that will apply to any tooltips created from now on. |
Examples:
// Set default options for all future tooltip instantiations $.tooltipster.setDefaults({ side: 'bottom', ... }); // The `instances` method, when used without a second parameter, allows you to access all tooltips present in the page. // That may be useful to close all tooltips at once for example: var instances = $.tooltipster.instances(); $.each(instances, function(i, instance){ instance.close(); }); $('.tooltip1').tooltipster(); $('.tooltip2').tooltipster(); // this method call will only return an array with the instances created for the elements that matched '.tooltip2' because that's the latest initializing call. var instances = $.tooltipster.instancesLatest();
Tooltipster makes it very easy to go from one of the packaged themes and customize a few properties of your choice. To do so, we recommend that you create a so-called "secondary theme" which will override some properties of a packaged theme.
Create a new css file and include it in your page. Inside the file, declare your customized rules like this:
/* This is how you would create a custom secondary theme on top of tooltipster-noir: */ .tooltipster-sidetip.tooltipster-noir.tooltipster-noir-customized .tooltipster-box { background: grey; border: 3px solid red; border-radius: 6px; box-shadow: 5px 5px 2px 0 rgba(0,0,0,0.4); } .tooltipster-sidetip.tooltipster-noir.tooltipster-noir-customized .tooltipster-content { color: blue; padding: 8px; }
For your secondary theme to be applied, provide an array of themes instead of just one. You may even provide more than two themes if you create a secondary theme to your secondary theme! In other words, this allows sub-themes, sub-sub-themes, etc. for your tooltips.
$('.tooltip').tooltipster({ theme: ['tooltipster-noir', 'tooltipster-noir-customized'] });
Changing the size of the arrow might be the only challenging customization but it's doable! We encourage you to see what we have done in the different themes and work from there.
It's easy as pie to update a tooltip's content - whether it's open or closed. Depending on your selector, you can update multiple tooltips at once or just one:
$('#myelement').tooltipster('content', 'My new content'); // or when you have the instance of the tooltip: instance.content('My new content');
Tooltipster plays a subtle animation when the content changes. This animation may be changed or disabled through the updateAnimation option.
Tooltipster gives you the ability to fire a custom function when a tooltip is initialized (functionInit), but also every time the tooltip is about to open (functionBefore), when it has opened (functionReady) or after it has closed (functionAfter).
One great use for this is to grab dynamic content for your tooltips via AJAX. In this example we will use functionBefore to load data the first time the tooltip is opened. Until the data has been loaded, we will display a "Loading..." notification:
$('.tooltip').tooltipster({ content: 'Loading...', // 'instance' is basically the tooltip. More details in the "Object-oriented Tooltipster" section. functionBefore: function(instance, helper) { var $origin = $(helper.origin); // we set a variable so the data is only loaded once via Ajax, not every time the tooltip opens if ($origin.data('loaded') !== true) { $.get('http://example.com/ajax.php', function(data) { // call the 'content' method to update the content of our tooltip with the returned data. // note: this content update will trigger an update animation (see the updateAnimation option) instance.content(data); // to remember that the data has been loaded $origin.data('loaded', true); }); } } });
In addition to this, you may provide a function as the callback argument of the open/close methods. If the tooltip is already in the state you are asking for (open & stable/closed), the callback is executed immediately. Please note that if the open/close action is somehow cancelled before it has completed its animation, the callback function will never be called.
$(document).ready(function() { $('.tooltip').tooltipster(); $('#example').tooltipster('open', function(instance, helper) { alert('The tooltip is now fully shown. Its content is: ' + instance.content()); }); $(window).keypress(function() { $('#example').tooltipster('close', function(instance, helper) { alert('The tooltip is now fully hidden'); }); }); });
Let's hover a little on how the side option works.
You have two options: provide either a string, like side: 'top', or an array of strings, like side: ['top', 'bottom'] for example.
This tells Tooltipster that you'd prefer the tooltip to be above the tooltipped element, but allows the tooltip to be positioned differently if need be.
This means that if there is not enough space on top for your tooltip, the other sides may be used a fallbacks. Here is the order of fallbacks, depending on what side you chose:
// ... is the same as ... 'top' => ['top', 'bottom', 'right', 'left'] 'bottom' => ['bottom', 'top', 'right', 'left'] 'right' => ['right', 'left', 'top', 'bottom'] 'left' => ['left', 'right', 'top', 'bottom']
There are two reasons to do so.
Firstly, if you are not happy with the four default orders of sides fallbacks. For example you might want: side: ['top', 'left', 'bottom', 'right'].
Secondly if you want to disable totally one or more sides. For example, with ['top', 'right', 'left'], the tooltip will never be positioned on the bottom. With ['right'], the tooltip will always be on the right, even if it has to overflow the document.
The easiest way to set when a tooltip should open or close is to set the trigger option to one of the two predefined values: 'hover' or 'click'.
You can see how they perform with our demos at the top of this page. Note that these two behaviors also apply to their touch-gesture equivalents.
If you feel that you need a different behavior or more flexibility, set the trigger option to 'custom' and read on.
There are many actions that may cause a tooltip to open or close, should we want to. These action are called "open triggers" and "close triggers".
Tooltipster supports a number of them out of the box, the list lies below. Plugins may provide support for additional triggers.
click When the origin is clicked by a mouse.
mouseenter When a mouse comes over the origin. The delay option is taken into account as the delay before opening.
touchstart When the origin is pressed on a touch screen. The delayTouch option is taken into account as the delay before opening.
tap When the origin is tapped (ie pressed and then released) on a touch screen.
click When a mouse click happens anywhere in the page. However, if the interactive option is set to true, a click happening inside the tooltip will not close it.
mouseleave When the mouse goes away from the origin. The delay option is taken into account as the delay before closing.
originClick When the origin is clicked by a mouse. This mimics a behavior that browsers usually have and is meant to be used with the mouseenter open trigger.
scroll When scrolling happens in the window or in a scrollable area which is a parent of the origin.
tap When the finger taps (ie presses and releases) anywhere in the touch screen.
touchleave When the finger is removed from the touch screen or if the interaction was stopped by the device. The delayTouch option is taken into account as the delay before closing.
Once that the trigger option is set to 'custom', all open and close triggers are disabled by default. Use the triggerOpen and triggerClose options to reactivate the triggers of your choice, as shown below.
Let's assume that you'd like a tooltip to open upon mouse hovering, but close only when either a mouse click or scrolling happens. Write this:
$('#example').tooltipster({ trigger: 'custom', triggerOpen: { mouseenter: true }, triggerClose: { click: true, scroll: true } });
This works well on desktops but not on touch devices, because we have not enabled any touch triggers. Let's fix this by enabling the touchstart and tap triggers as well:
$('#example').tooltipster({ trigger: 'custom', triggerOpen: { mouseenter: true, touchstart: true }, triggerClose: { click: true, scroll: true, tap: true } });
Good question. Setting trigger: 'hover' or trigger: 'click' is nothing but a shorthand.
Having trigger: 'hover' is actually the same as having:
$('#example').tooltipster({ trigger: 'custom', triggerOpen: { mouseenter: true, touchstart: true }, triggerClose: { mouseleave: true, originClick: true, touchleave: true } });
And having trigger: 'click' is the same as having:
$('#example').tooltipster({ trigger: 'custom', triggerOpen: { click: true, tap: true }, triggerClose: { click: true, tap: true } });
In parallel to (or instead of) using the built-in triggers, you may want to open/close a tooltip yourself on a specific occasion.
To achieve this, Tooltipster has the open and close methods. Both of them may receive an optional callback argument, which represents a function you'd like to be called when the tooltip is done animating.
Here's an example of how you could launch a specific tooltip on page load and close it when any key on your keyboard is pressed.
<span id="example" class="tooltip" title="My tooltip content">Example</span>
$(document).ready(function() { // first on page load, initialize all tooltips $('.tooltip').tooltipster(); // then immediately open the tooltip of the element named "example" $('#example').tooltipster('open'); // as soon as a key is pressed on the keyboard, close the tooltip. $(window).keypress(function() { $('#example').tooltipster('close'); }); });
This is for advanced users who are comfortable with Javascript and CSS.
When the tooltip needs to be positioned or repositioned, Tooltipster runs all kinds of tests to find the best option. But before the computed position is applied, you have the option to edit it using the functionPosition option.
When you provide custom coordinates for the tooltip and its arrow, they have to be relative to the top and left edges of the viewport. This makes custom positioning in Tooltipster both very fast and very simple. Doing your calculations, element.getBoundingClientRect will become your new best friend, so make sure you check it out.
Your functionPosition callback is called with three parameters. The first two ones are instance and a helper, as usual. The third argument is an object with the position properties proposed by Tooltipster, that you may edit. You must return the edited third argument for the changes to get applied.
helper.mode (will be 'natural' or 'constrained') indicates if Tooltipster adapted the size of the tooltip for it to fit in.
helper.tooltipClone is a clone of the tooltip which exists in the DOM at the time the callback is called.
helper.geo includes useful pre-calculated data about the page layout. It will help you avoid putting the tooltip accidentally off screen, for example. This object is in this form:
{ document: { size: { height: integer, width: integer } }, window: { scroll: { left: integer, top: integer }, size: { height: integer, width: integer } }, origin: { // the origin has a fixed lineage if itself or one of its ancestors has a fixed position fixedLineage: boolean, offset: { // this is the distance between the bottom side of the origin and the top of the document bottom: integer, left: integer, // this is the distance between the right side of the origin and the left of the document right: integer, top: integer }, size: { height: integer, width: integer }, // if the origin is a map area, this will hold the associated image element usemapImage: HTMLobject || null, windowOffset: { // this is the distance between the bottom side of the origin and the top of the viewport bottom: integer, left: integer, // this is the distance between the right side of the origin and the left of the viewport right: integer, top: integer } } }
The third argument is in the form:
{ coord: { left: number, top: number }, distance: number, side: string, size: { height: number, width: number }, target: number }
coord properties determine the position of the tooltip and are relative to the viewport.
distance is the offset that will be applied between the origin and the tooltip.
side is the side Tooltipster has judged best for your tooltip, according to your requirements.
size properties tell you the size that your tooltip will have. It is either the natural size of the tooltip, or a size that has been set by Tooltipster to fit best on screen according to your requirements.
target represents the location Tooltipster thinks the tooltip should ideally be centered on, and the arrow aiming at. It is given as the distance from the relevant edge of the viewport (left edge if the side is "top" or "bottom", top edge if the side is "left" or "right"). The target is usually the middle of the origin, but can be somewhere else when the origin is actually a portion of text split in several lines. Editing this value will change the location the arrow is aiming at but will not change the position of the tooltip itself (use coord for that).
You may look at the source code of this documentation to see how the custom positioning demo at the top of this page was made. Here is the simplest example, let's just move the tooltip by 10 pixels to the bottom-right:
$('#my-tooltip').tooltipster({ functionPosition: function(instance, helper, position){ position.coord.top += 10; position.coord.left += 10; return position; } });
Instead of using the data-tooltip-content attribute, you may:
$('#tooltip').tooltipster({ content: $('#tooltip_content'), // if you use a single element as content for several tooltips, set this option to true contentCloning: false });
Tooltipster's content method allows you to edit the content of the tooltip at any time with greater flexibility. If you had this HTML for example:
<div class="tooltip"> This div has a tooltip with HTML when you hover over it! <span class="tooltip_content"> <img src="myimage.png" /> <strong>This is the content of my tooltip!</strong> </span> </div>
You could do this upon initialization:
$('.tooltip').tooltipster({ functionInit: function(instance, helper){ var content = $(helper.origin).find('.tooltip_content').detach(); instance.content(content); } });
If you write encoded HTML in the title attribute and set the contentAsHTML option to true, it will be displayed as HTML in the tooltip.
You may want to write options on a per-tooltip basis, directly in your HTML. Of course, you should try to do this for options which are "inlinable" only. Anyway, that's a great opportunity to make use of the functionInit option and the option method, here's how it goes:
<span class="tooltip" data-tooltipster='{"side":"left","animation":"slide"}' title="Hello">World</span>
$('.tooltip').tooltipster({ functionInit: function(instance, helper){ var $origin = $(helper.origin), dataOptions = $origin.attr('data-tooltipster'); if(dataOptions){ dataOptions = JSON.parse(dataOptions); $.each(dataOptions, function(name, option){ instance.option(name, option); }); } } });
Pro tip: for more flexibility, achieve the same with the event system: $.tooltipster.on('init', function(event) {...});. See the event-driven section.
Sometimes it's easier to work with data sets that you will format before display, rather than format them on the server side. For example, what if you could turn this:
<span id="example" title="We have 3 people today. Say hello to Sarah, John, Matthew">People</span>
into this:
<span id="example" title='["Sarah", "John", "Matthew"]'>People</span>
...with exactly the same result in the tooltip? A first way of doing this is to format upon initialization:
$('#example').tooltipster({ functionInit: function(instance, helper){ // parse the content var content = instance.content(), people = JSON.parse(content), // and use it to make a sentence newContent = 'We have ' + people.length + ' people today. Say hello to ' + people.join(', '); // save the edited content instance.content(newContent); } }); // this logs: "We have 3 people today. Say hello to Sarah, John, Matthew" console.log($('#example').tooltipster('content'));
Simple, right? It works, however this is not ideal for us if we need to get ahold of our data set later. Because as you can see, when we call the content method, we get the computed sentence, not our initial data set. No worries, the functionFormat option is here to help us.
$('#example').tooltipster({ functionInit: function(instance, helper){ var content = instance.content(), people = JSON.parse(content); instance.content(people); }, // this formats the content on the fly when it needs to be displayed but does not modify its value functionFormat: function(instance, helper, content){ var displayedContent = 'We have ' + content.length + ' people today. Say hello to ' + content.join(', '); return displayedContent; } }); // Alright! this logs: ["Sarah", "John", "Matthew"] console.log($('#example').tooltipster('content'));
The status method returns an object that contains information about the tooltip. Here is this object with the meaning of each property:
{ // if the tooltip has been destroyed destroyed: boolean, // if the tooltip is scheduled for destruction (which means that the tooltip is currently closing and may not be reopened) destroying: boolean, // if the tooltip is enabled enabled: boolean, // if the tooltip is open (either appearing, stable or disappearing) open: boolean, // the state equals one of these four values: state: 'appearing' || 'stable' || 'disappearing' || 'closed' }
So far, quite often we called instance methods like this: $(...).tooltipster(methodName). However, advanced users may prefer to handle objects directly rather that go through the DOM to manipulate their tooltips. That's possible with Tooltipster!
Here is an example. This:
$('#my-element').tooltipster(); $('#my-element').tooltipster('open').tooltipster('content', 'My new content');
...can also be written like this:
$('#my-element').tooltipster(); var instance = $('#my-element').tooltipster('instance'); instance.open().content('My new content');
What happened here? The instance method returns the Tooltipster instance that corresponds to the first tooltip set on #my-element. Once we have the Tooltipster instance that corresponds to a tooltip, we can call any methods directly on it to manipulate the tooltip.
If multiple tooltips were set on #my-element using the multiple option (see next section), we'd have to call $.tooltipster.instances('#my-element'); to get an array with all the instances.
As you've seen in many previous examples involving callbacks - either functionInit, functionBefore, etc., open/close callbacks, they all get the Tooltipster instance that calls them as first parameter. So this works fine:
$('#origin').tooltipster({ functionBefore: function(instance, helper){ instance.content('Random content'); } });
While you may feel that this is only nice to have, this notation actually becomes compulsory when you start using multiple tooltips on a same element.
Several independent tooltips can be set on a single element, each one having its own triggers and options. Just set the multiple option to true when you initialize your tooltip. There is just something you need to be aware of when using multiple tooltips:
Calling a method this way: $(...).tooltipster(methodName [, argument]) only ever calls the method on the first tooltip that was set on the element. That's an issue when you actually want to manipulate the second or third tooltip! Make sure you read the previous section as we have to manipulate Tooltipster instances instead to solve this.
var $myElement = $('#my-element'); // create a first tooltip as usual. The multiple option is actually optional for the first tooltip $myElement.tooltipster({ content: 'My first tooltip', side: 'top' }); // initialize a second tooltip $myElement.tooltipster({ // don't forget to provide content here as the first tooltip will have deleted the original title attribute of the element content: 'My second tooltip', multiple: true, side: 'bottom' }); var instances = $.tooltipster.instances($myElement); // use the instances to make any method calls on the tooltips instances[0].content('New content for my first tooltip').open(); instances[1].content('New content for my second tooltip').open(); // WARNING: calling methods in the usual way only affects the first tooltip that was created on the element $myElement.tooltipster('content', 'New content for my first tooltip')
When you provide user callbacks (functionInit, functionBefore etc.), it is also crucial to work with the current instance:
$('#my-element').tooltipster({ content: 'HELLO', functionInit: function(instance, helper) { var string = instance.content(); instance.content(string.toLowerCase()); }, multiple: true });
Live binding does not come out of the box with Tooltipster but is easy to implement if that's what you want.
We chose not to include that option directly because there is no solution that would be both 100% reliable and fast at the same time, and we wanted you to be aware of it before you proceeded. We recommend that you initialize tooltips manually after you create elements that should be tooltipped, in order to avoid any surprises. We do not provide support for issues that might arise from live binding.
If you go the delegation way, you will rely on the bubbling of events (mouseenter or click) triggered on their origin. That may be an issue if these events are stopped from bubbling at some point, and you might run into race conditions depending on how you handle things. And of course, the tooltips won't be initialized until their origin is hovered/clicked, which may be an issue if you wish to manipulate them programmatically or if you use a plugin which is supposed to start working before the tooltip opens.
If you understand these caveats and are willing to proceed, the code below will do the work. You might want to change '.tooltip' to something else and switch from 'mouseenter' to 'click' if you want a click trigger.
$('body').on('mouseenter', '.tooltip:not(.tooltipstered)', function(){ $(this) .tooltipster({ ... }) .tooltipster('open'); });
On the other hand, using mutation observers to initialize tooltips when elements are added to the DOM should completely reliable, but is known to severely hinder the performances of the application. Should you go down this road, feel free to share your code with us and we'll publish it here.
Advanced users may take advantage of the many events that Tooltipster triggers during its tasks. Events and listeners give you more flexibility and greater control over Tooltipster's mechanics.
For example, instead of having to provide a single monolithic callback to functionBefore and the like, events allow you to easily bind and unbind several callbacks at any time. This:
$("#my-tooltip").tooltipster({ functionBefore: function(instance, helper){ doThis(); doThat(); } });
... can be written like that:
var instance = $("#my-tooltip").tooltipster({}).tooltipster('instance'); instance .on('before', doThis) .on('before', doThat);
Set your listeners on a per-instance basis using jQuery's syntax: instance.on(), instance.one(), instance.off() and instance.triggerHandler().
Core listeners that listen to all instances are possible: $.tooltipster.on(), $.tooltipster.one(), $.tooltipster.off(), $.tooltipster.triggerHandler().
Core listeners are great way to set default callbacks without writing something like $.tooltipster.setDefaults({ functionBefore: myFunction }), which could potentially be overriden at initialization. For example, both doThis and doThat will be called here:
$.tooltipster.on('init', function(event){ doThis(); }); $("#my-tooltip").tooltipster({ functionInit: doThat });
Remark: the events are sent to the core listeners first. Besides, the instance emitters and the core emitter are different objects, so unbinding a listener from the core emitter will not unbind it from instance emitters, if you ever bound it to both.
The init, before, ready, after, format and position events will sound familiar: they happen at the same time as their equivalent functionInit, etc.
But there are many others that you or plugin makers can use. Your listeners will get one argument, the event, which holds useful properties: event.type, event.instance, event.origin, event.event (when there is one, similarly to the usual helper.event) and potentially others as described below. These are all the possible events:
before has a special event.stop property which is a function you may call to prevent the tooltip from opening.
close happens at the start of the closing animation. Note: during the animation, the closing may be still cancelled if the tooltip is reopened. The event has a special event.stop property which is a function you may call to ignore the closing order.
closing happens at the end of the closing animation, when you know for sure that the tooltip is about to be closed. If you think you need this event, you may be wrong! When the tooltip is closed, remember that the content is just detached from the DOM and still accessible via the content method.
created is meant for plugin makers and happens when an HTML element has been created for the tooltip.
destroy events happen when the tooltip is closed and about to be destroyed.
destroyed events happen when the tooltip has been destroyed.
dismissable events affect the closing of the tooltip when the mouseleave and touchleave close triggers are used. Read the source for more information.
format has a special event.format property which is a function you may use to format the content before display. Just provide your formatted content as first argument. For your convenience, the original content is provided in the event.content property.
geometry happens when Tooltipster determines the size and coordinates of the origin, in order to know where to place the tooltip. The computed properties (left, top, width and height) are passed in the event.geometry object. It has a special event.edit property which is a function you may use to provide this information yourself. Just provide the edited geometry object as first argument. In some cases, this may be easier to use than functionPosition as it allows you to provide a specific target without having to compute the final position yourself.
init is triggered upon tooltip initialization and may thus be heard only by a core listener.
position happens during the positioning process and can be used to provide a custom position (see functionPosition). The proposed position is present in event.position. The special event.edit property is the function you may call with your edited positioning values as first argument.
positionTest happens before position, while sideTip is still evaluating the different positioning scenarios. While less straightforward to handle, it also brings the possibility to switch between scenarios more easily. As this gets more complex, please read the source code or ask for support about this.
positionTested is related to positionTest.
reposition is meant for plugin makers and happens when Tooltipster thinks the tooltip should be repositioned.
repositioned happens after Tooltipster repositioned of the tooltip. The event has a special event.position with positioning information.
scroll happens whenever a parent of the origin is scrolled. The native scroll event is passed as event.event. If the scroll event was triggered on another element than the window, a special event.geo property gives you information about the page and the origin.
start happens when the mouseenter or touchstart open triggers are used and that the origin gets mouseover/touched. The event has a special event.stop property which is a function you may call to prevent the tooltip from opening.
startcancel happens after start at the end of the opening delay (see the delay option) if the tooltip is not to be opened.
startend happens after start at the end of the opening delay (see the delay option) if the tooltip may be opened.
state happens every time the tooltip enters a different state. The state value is held in event.state and may be 'appearing', 'stable', 'disappearing' or 'closed'.
updated happens when a call to the content method has updated the content. The event has a special event.content property.
Tooltipster is composed of a main script and one or several plugins.
By default, sideTip is the only plugin used by Tooltipster. sideTip takes care of positioning tooltips on a side of their origin.
In fact, the name of our main file is tooltipster.bundle.js because it is a bundle of tooltipster.main and tooltipster-sideTip.
Most of the time, using a plugin requires that you specify its name in the options of the plugin:
$('#example').tooltipster({ plugins: ['pluginNamespace.pluginName'] });
The plugin's namespace exists to resolve conflicts, in case two plugins decided to have the same name, or options/methods of the same name.
Several plugins may be used at the same time and be listed together in the plugins option. However, plugins are sometimes incompatible, for example sideTip and follower (a tooltip obviously can't be positioned on a side and follow the cursor at the same time).
Sometimes, when a plugin adds no options or instance methods, or is auto-activated, you might not have to declare it in the options. Anyway, each plugin will give you its installation instructions.
Under the hood, Tooltipster's plugin system is built on our event system. Plugins register to the core and may react to Tooltipster's many events. A guide for plugin creation is available [here](https://github.com/calebjacob/tooltipster/blob/master/plugins.md).
Let us know if you decide to create and share your own plugin, we will list it here!
Several plugins may have the same name. To resolve the conflict, provide the namespace of the plugin when you declare it in the options. You can get the namespace of a plugin by looking at its source file. For example:
$('#example').tooltipster({ plugins: ['laa.follower'] });
Several plugins may have options of the same name. To resolve the conflict, wrap the options of plugins under a property with their full name. For example:
$('#example').tooltipster({ content: 'Hello', theme: 'tooltipster-noir', 'laa.follower': { anchor: 'top-center' }, 'some.otherPlugin': { anchor: 'value' } });
Several plugins may have methods of the same name. To resolve the conflict, use the instance object of the tooltip and specify the full name of the desired plugin in your calls. For example:
$('#example').tooltipster({ functionBefore: function(instance, helper) { instance['laa.follower'].methodName(); } });
The default sideTip plugin adds a few options to Tooltipster. For the sake of simplicity, these options were listed previously among the main options in the Options section. But if you decide not to use sideTip, these options will actually not be available anymore, except if another plugin offers options of the same name. These specific options are:
arrow, distance, functionPosition, minIntersection, minWidth, maxWidth, side, viewportAware
The position, positionTest and positionTested events are also specific to sideTip.
The question comes frequently, so here is the answer: yes, it's possible. Here is an example:
<strong id="nesting">Hover me!</strong>
$('#nesting').tooltipster({ content: $('<span>Hover me too!</span>'), functionReady: function(instance, helper){ // the nested tooltip must be initialized once the first tooltip is open, that's why we do this inside functionReady() instance.content().tooltipster({ content: 'I am a nested tooltip!', distance: 0 }); }, interactive: true });
Result : Hover me!
When the user hovers on adjacent elements one after the other to read their tooltips, you may wish to display the tooltips instantly rather than wait for the default delay and animation times. A demonstration is worth a thousand words, so check out this example:
...and now this one:
This is a good opportunity to demonstrate Tooltipster's powerful features. This is the HTML we wrote:
<input type="button" value="❤" title="Add to favorites" class="tooltip tooltip_group" /> <input type="button" value="☂" title="Dance in the rain" class="tooltip tooltip_group" /> <input type="button" value="♞" title="Play chess" class="tooltip tooltip_group" /> <input type="button" value="☯" title="Turn off the computer and meditate" class="tooltip tooltip_group" />
... and the Javascript (which looks long with the comments, but is actually short and simple):
// initialize tooltips in the page as usual $('.tooltip').tooltipster(); // bind on start events (triggered on mouseenter) $.tooltipster.on('start', function(event) { if ($(event.instance.elementOrigin()).hasClass('tooltip_group')) { var instances = $.tooltipster.instances('.tooltip_group'), open = false, duration; $.each(instances, function (i, instance) { if (instance !== event.instance) { // if another instance is already open if (instance.status().open){ open = true; // get the current animationDuration duration = instance.option('animationDuration'); // close the tooltip without animation instance.option('animationDuration', 0); instance.close(); // restore the animationDuration to its normal value instance.option('animationDuration', duration); } } }); // if another instance was open if (open) { duration = event.instance.option('animationDuration'); // open the tooltip without animation event.instance.option('animationDuration', 0); event.instance.open(); // restore the animationDuration to its normal value event.instance.option('animationDuration', duration); // now that we have opened the tooltip, the hover trigger must be stopped event.stop(); } } });
For your convenience, this has been turned into a Tooltipster plugin available here.
If you are going to work with SVG, you'll want to include our SVG plugin that brings fixes and improvements for SVG elements:
<head> <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.0.min.js"></script> <script type="text/javascript" src="tooltipster/dist/js/tooltipster.bundle.min.js"></script> <script type="text/javascript" src="tooltipster/dist/js/plugins/tooltipster/SVG/tooltipster-SVG.min.js"></script> </head>
If you want optimal results, you should consider including SVG.js and its ScreenBBox plugin in your page.
Why? Because browsers do not always make our life easy when it comes to working with SVG. Determining the coordinates of SVG paths, polylines or polygons is especially difficult since the native getBoundingClientRect, getBBox and other methods produce inaccurate results in most browsers (as of today in 2016). The result is that by default, the position of tooltips on SVG elements may be completely off. Fortunately, SVG.js helps in that matter and our plugin leverages its power out of the box. Just include the files in your page and that's it, Tooltipster will use them out of the box for optimal results.
For those who seek even more control over positioning, the position event (or the corresponding functionPosition option) and the geometry event allow you to set the exact position of the tooltip yourself.
The W3C issued a recommendation to make websites more accessible to persons with disabilities. This recommendation is known as WAI-ARIA (or simply ARIA), which stands for Web Accessibility Initiative - Accessible Rich Internet Applications.
Accessible tooltips can be powered by Tooltipster. To do this, one solution is to actually manipulate in parallel two tooltips which will share the same content :
- the ARIA tooltip, which is invisible on the screen but readable by ARIA-compatible software
- the Tooltipster tooltip, which is visible on the screen but does not appear as an ARIA-compatible element
A basic example : imagine that we want to put a tooltip on a text input field. As for the HTML part, you would write :
<input id="myfield" type="text" aria-describedby="myfield_description" /> <span id="myfield_description" role="tooltip">Please insert your name here</span>
As for the CSS part, write this :
#myfield_description { position: absolute; visibility: hidden; }
And finally, you could initialize Tooltipster like this :
$('#myfield').tooltipster({ functionInit: function(instance, helper){ var content = $('#myfield_description').html(); instance.content(content); }, functionReady: function(instance, helper){ $('#myfield_description').attr('aria-hidden', false); }, functionAfter: function(instance, helper){ $('#myfield_description').attr('aria-hidden', true); } }); // if in addition you want the tooltip to be displayed when the field gets focus, add these custom triggers : $('#myfield') .focus(function(){ $(this).tooltipster('open'); }) .blur(function(){ $(this).tooltipster('close'); });
Using Tooltipster alongside jQuery Validate by sparky672
Using Tooltipster alongside Clipboard.js
An Angular directive for Tooltipster by campbeln
Did you do something awesome with Tooltipster? Tell us and we'll post it up here!
Please head over to Stackoverflow or another help forum and let the community help you!
Head on over to Tooltipster's issue tracker on GitHub: https://github.com/calebjacob/tooltipster/issues
Before opening a new issue, please be sure to search through the backlog to see if your bug has already been submitted. Thank you! :)
Please use the interactive option.
That's because the size of your content inside the tooltip changes after Tooltipster positioned the tooltip.
This typically happens when you put images inside the tooltip. The first time it opens, the image is not loaded yet and thus has no size, so Tooltipster basically computes a position as if there were no images. A few milliseconds later, when the image has loaded, the tooltip gets bigger but is not automatically repositioned. The second time the tooltip opens, the image is already in cache and is ready for display, so Tooltipster can compute an appropriate position.
If the error still occurs, please open an issue on GitHub.
No, it's not Tooltipster's job to tamper with your content in any way. Besides, <script> tags are not the only possible threat (read some good advice).
It's really up to you to decide what should be sanitized before display. You may use functionInit, functionBefore or functionFormat to do so.
These elements do not trigger events anymore when they are disabled, which will cause Tooltipster to malfunction. There is no way around it, so we suggest you make them "look" disabled with CSS and Javascript, but do not set the actual `disabled` property on them. Or you could set pointer-events: none on your disabled element, wrap it in a container and put the tooltip on the container instead.
Tooltipster works "decently" down to IE6. However, these caveats should be noted:
This list is not exhaustive. You may report an issue if you detect one, we will answer but we cannot guaranty that a fix will be provided.