Tooltipster

一款基于JQ,灵活可扩展的插件
简单,强大,能胜任一切

Chrome FireFox Opera Safari Internet Explorer

Demos


Lorem ipsum dolor sit amet
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu.

I'm the most accurate tooltip ever! Let me fit to your layout the way you want to. I'm great to create menus too :)

Getting Started

1. 引入jQuery和Tooltipster's文件

你可以 点击这里下载, 引入 jQuery 和 Tooltipster's CSS 还有 JavaScript 文件在你的页面

<head>
<link rel="stylesheet" type="text/css" href="tooltipster/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/js/tooltipster.bundle.min.js"></script>
</head>

兼容提醒: jQuery 1.7已经足够了,除非你需要SVG兼容IE(需要使用jQuery 1.10+). Tooltipster 不能正常运行在IE9中引用jQuery1.8

2. 设置你的HTML

想让一个元素加入工具提醒, 我们会给他加上一个类名class 'tooltip' . 你也可以选择使用自定义的类名或选择器(请继续往下看), 由你决定. 之后, 我们将设置标题title 属性为我们想要的提示. 这里有几个栗子:

// 在图片加入工具提醒:
<img src="my-image.png" class="tooltip" title="This is my image's tooltip message!" />

// 在文字加入工具提醒 (span, div or whatever):
<span class="tooltip" title="This is my span's tooltip message!">Some text</span>

注意:如果您使用Twitter's Bootstrap,请使用另一个类名,因为“工具提示”会产生冲突。

3. 激活 Tooltipster

我们要做的最后一件事是激活Tooltipster. 我们需要在头部得问 </head> 标签加入script并激活Tooltipster (你可以选择使用自己定义的选择器 - 我们的栗子是使用 'tooltip' class):

<head>
...
<script>
	$(document).ready(function() {
		$('.tooltip').tooltipster();
	});
</script>
</head>

4. 定义你的tooltips风格

第一个是默认样式, Tooltipster还为你提供另外五种主题风格.

Default
Light
Borderless
Punk
Noir
Shadow

要使用这些主题,需要引用一个css文件 (他的路径是 css/plugins/tooltipster/sideTip/themes 文件里) 在你的页面并指定其名称在Tooltipster's 选项

$('.tooltip').tooltipster({
theme: 'tooltipster-noir' //使用Noir主题
});

你可以通过修改tooltips的样式达到你想要的效果, 自定义主题部分 在下面等着你.

注: "sideTip" 是 Tooltipster默认插件的名称. 我们稍后会看到这个插件.

5. 在HTML内使用你的tooltips

Tooltipster 允许你使用任何HTML标记触发提醒. 这意味着可以插入像图像和文本格式标记之类的东西。.

代替之前加入的title 属性, 这次我们使用 data-tooltip-content 属性来提供与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>

在你的CSS文件, 加入 .tooltip_templates { display: none; } 这样内容不会在工具提示之外显示出来.

重点: 如果你有两个(或以上)的tooltips有相同的 data-tooltip-content 属性 (也就是说, 你想用一样的HTML元素), 请将 contentCloning 选项设置为 true 当你初始化你的tooltips:

$('.tooltip').tooltipster({
contentCloning: true
});

注: 其实还有其他设置提醒内容的方法.

6. 使用插件

Tooltipster的功能可以通过插件扩展.他们可能会增加新的风格,新的选择,新的方法,新的行为,等等.
Tooltipster的一些流行插件:

sideTip Tooltipster附带的和默认启动的

SVG Tooltipster附带的, 增加了 SVG 支持, 但是默认情况是不启动的 (详情见SVG section)

follower 让工具提示跟随光标 有空看看这

scrollableTip 使工具提示增加滚动条当内容过多. 请看这

discovery 创建工具提示组更快显示 ,在分组提示 部分显示, 可以看这

selectableText 当你选择/高亮某段文字,让工具提醒显示. 详情见此

有关插件的更多信息,请阅读我们的。插件部分.

参数

Tooltipster 的参数(选项)给你一个宽阔的可变范围来调整成你心仪的提醒. 这里教你如何配置参数:

$('.tooltip').tooltipster({
animation: 'fade',
delay: 200,
theme: 'tooltipster-punk',
trigger: 'click'
});

这里是全部可用参数的列表:

参数 可用的值 描述

animation

'fade',
'grow',
'swing',
'slide',
'fall'
决定tooltips进场的动画. 除了内置的动画, 你也可以创建自定义动画在你的CSS文件. 在IE9及以下, 所有动画默认为javascript生成淡入动画. 默认值: 'fade'

animationDuration

integer,
integer[]
设置动画的持续时间, 以毫秒为单位. 如果你想为你的tooltips打开/关闭提供不同的持续时间, 你可以提供一个数组来表示不同的值(如:integer[400,500]). 默认值: 350

arrow

boolean 给你的tooltips加一个"气泡" 箭头. 默认值: true

content

string,
jQuery object,
any
如果设置了, 将会覆盖tooltips的内容. 如果您提供的内容不是字符串或jQuery封装的HTML元素,你需要使用'functionFormat'这个参数来格式化你的内容以达到显示效果默认值: null

contentAsHTML

boolean 如果tooltip的内容是字符串, 会默认显示为纯文本. 如果想将内容解析为HTML, 请将这个参数设为true. 默认值: false

contentCloning

boolean 如果你提供了一个JQ对象给'content'这个参数,如果这个克隆对象应该被使用,则设置此参数.默认值: false

debug

boolean 当你做了你不应该做的事情,tooltipster日志提醒和通知会在控制台报错,如果你设置了false便可以禁用日志记录默认值: true

delay

integer,
integer[]
在鼠标交互的时候,这个属性是在hover/trigger..触发tooltip开始打开或者关闭动画使用时生效(简单来说就是一个延时器)(*). 如果你想为你的tooltips打开/关闭提供不同的持续时间, 你可以提供一个数组来表示不同的值(如:integer[400,500]).默认值: 300

delayTouch

integer,
integer[]
在触摸交互的时候, 同上(*).如果你想为你的tooltips打开/关闭提供不同的持续时间, 你可以提供一个数组来表示不同的值(如:integer[400,500]). 默认值: [300, 500]

distance

integer,
integer[]
以像素为单位,远点到提醒工具的距离.如果您希望为每个边指定不同的距离,则该值可以是整数或整数数组(通常为CSS语法)。 默认值: 6

functionInit

function 在实例化时只被触发一次的自定义函数. Arguments. 默认值: none (null)

functionBefore

function 在打开工具提示之前要触发的自定义函数. 这个发方法会阻止tooltip打开如果返回false.Arguments. 默认值: none (null)

functionReady

function 当工具提示及其内容被添加到DOM时,将触发自定义函数. Arguments. 默认值: none (null)

functionAfter

function 一旦工具提示已关闭并从DOM中移除,则将定制一个函数.Arguments. 默认值: none (null)

functionFormat

function 格式化内容的函数.它得到两个第一个通常的参数和第三个参数的内容。它必须返回在工具提示中显示的值,无论是字符串还是jQuery封装的HTML元素(请参阅格式化部分). 默认值: none (null)

functionPosition

function 当tooltip重新定位时触发的自定义函数,它给你轻微或完全修改的位置,Tooltipster是要给tooltip的能力,它将建议的放置值集设置为第三个参数.函数必须返回您可能编辑过的位置值集合(请参阅定位部分). 默认值: none (null)

IEmin

integer 要运行的IE的最低版本. 默认值: 6

interactive

boolean 在工具提醒给用户尽可能多的交互.如果你想他们在工具提醒内容可以点击,填写表格或者其他交互,你就必须把这个参数设置为true.当使用“悬停”关闭触发器时,用户必须在开始关闭之前将光标移到工具提示上(此时间间隔由“delay”参数设置). 默认值: false

maxWidth

integer 设置tooltip的最大宽度. 默认值: null (无限制)

minIntersection

integer 对应于箭头中心和工具提示边缘之间强制执行的最小距离. 主要用于创建大于默认主题的箭头. 默认值: 16

minWidth

integer 设置tooltip的最小宽度.默认值: 0 (auto width)

multiple

boolean 允许你把几个提示在一个单一的元素 (详见 multiple 部分). 默认值: false

plugins

string[] 设置使用Tooltipster的插件名. 默认值: ['sideTip']

repositionOnScroll

boolean 为了使tooltip尽可能长时间可见,重新定位tooltip如果它在用户滚动页面时退出视窗. 默认值: false

restoration

'none',
'previous',
'current'
指定在调用“销毁”方法后,是否应该在HTML元素上恢复title属性.这个属性可以省略,或是在Tooltipster之前初始化存在的值恢复,或是与字符串化值的当前内容恢复.注意:在多个工具提示的情况下在一个单一的元素,只有最后的破坏可能会触发恢复提示. 默认值: 'none'

selfDestruction

boolean 在这个原点从DOM移除后,设置这个参数是否将tooltip自毁.这可以防止内存泄露. 默认值: true

side

string,
string[]
设置tooltip在哪侧显示. 这个值可能是一个: 'top', 'bottom', 'left', 'right'. 也可以是一个数组包括多个值. 当使用数组时,这些值的顺序要考虑到回退顺序和禁用没有用到的一侧 (see the sides section). 默认值: ['top', 'bottom', 'right', 'left']

timer

integer 设置这个工具提醒在关闭前的显示时间(以毫秒为单位) 默认值: 0 (disabled)

theme

string,
string[]
设置一个将覆盖默认工具提示外观的主题. 你可以提供多个字符串的数组来同时应用多个主题Y(详见 主题部分). 默认值: empty array

trackerInterval

integer 设置追踪程序持续时间/毫秒(见trackOrigin 和 trackTooltip).当工具提醒被打开,即使trackOrigin和trackTooltip设置为false,追踪器运行会检查起点是否被移除,如非必要,你定的值不能太高或太低. 默认值: 500

trackOrigin

boolean 如果原点移动或调整大小需要复位提醒.由于此选项可能对性能有影响,我们建议您仅在需要时启用它. 默认值: false

trackTooltip

boolean 如果tooltip改变大小则重新配置tooltip.当尺寸受到'content'这个方法而改变尺寸,tooltip已经重新定位而不需要这个参数。由于此选项可能对性能有影响,我们建议您仅在需要时启用它。详情进入这个入口 有常见问题解答 默认值: false

trigger

'hover',
'click',
'custom'
设置这个触发条件,有'click','hover',还可以自定义以达到你想要的效果. 见 触发器部分 来学习如何使用自定义触发器. 默认值: 'hover'

triggerClose

object 当你把'trigger'设置为'custom',所有内置关闭触发器都默认不可用,此参数就是允许您激活您所选择的触发器来创建一个定制的行为,只在设置'trigger'为'custom'时有效。 详见触发器部分.

triggerOpen

object 类似于'triggerClose'(同上).

updateAnimation

'fade',
'rotate',
'scale',
null
用于打开tooltip后的后续动画设置,你可以创建自己的动画在您的CSS文件内但是要将值设为'null'. 默认值: 'rotate'

viewportAware

boolean 尝试将tooltip放置在屏幕打开时完全可见的地方,如果工具提示在其源于屏幕之外(使用方法调用)打开时,您可能希望将此选项设置为false。默认值: true

zIndex

integer 设置tooltip的z-index默认值: 9999999


传递给回调函数的参数

几乎所有用户的回调函数有相同的特征. 这意味着 functionInit, functionBefore, functionReady, functionAfter, functionFormat, functionPosition and the open and close 回调都得到了这两个参数:

// this is valid for the other callback functions too
functionInit(instance, helper){
...
}

小例外: functionFormatfunctionPosition 获取额外的第三个参数(以上记载)。

instance 是调用回调函数对象和Tooltipster 面向对象部分object-oriented section的描述.

helper 是一个对象,其中包含您可能会发现有用的变量. 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.

Methods

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

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

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();

Common use cases

Styling your tooltips with a custom look

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.

Updating a tooltip's content

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.

Using AJAX to generate your tooltip content

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');
	});
});
});

Forcing or disabling sides

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.

What happens when I provide a string, like 'top' ?

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']

When should I provide an array instead ?

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.

Opening and closing a tooltip: the built-in triggers

Predefined behaviors

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.

Creating a customized behavior

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.

1) Open 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.

2) Close triggers

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.

Examples

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
}
});
« Ok but wait... then what do the predefined 'hover' and 'click' behaviors do exactly? »

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
}
});

Opening and closing a tooltip: the method calls

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');
});
});

Achieving custom positioning

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;
}
});

Alternative ways of setting HTML content

Instead of using the data-tooltip-content attribute, you may:

a) Provide HTML content in the options

$('#tooltip').tooltipster({
content: $('#tooltip_content'),
// if you use a single element as content for several tooltips, set this option to true
contentCloning: false
});

b) Set HTML content with a method call

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);
}
});

c) Deprecated: writing encoded HTML in the title attribute.

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.

Specifiying options through data-attributes

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.

Working with data sets

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'));	
		

Status: getting information about the tooltip

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'
}

Object-oriented Tooltipster

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.

Using multiple tooltips on a single 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
});

Dynamic live binding on newly created elements

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.

Event-driven Tooltipster

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.

Event types

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's plugin system

General information

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/iamceege/tooltipster/blob/master/plugins.md).

Let us know if you decide to create and share your own plugin, we will list it here!

Handling conflicts between plugins

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();
}
});

A note about sideTip

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.

Nested tooltips

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!

Grouped tooltips

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.

Tooltips on SVG elements

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/js/tooltipster.bundle.min.js"></script>
<script type="text/javascript" src="tooltipster/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.

Making tooltips accessible to persons with disabilities

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');
});

Community submitted use cases

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!

Frequently asked questions

"I need help to implement Tooltipster"

Please head over to Stackoverflow or another help forum and let the community help you!

"I found a bug, how do I reach you?"

Head on over to Tooltipster's issue tracker on GitHub: https://github.com/iamceege/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! :)

"I can't click in the tooltip"

Please use the interactive option.

"The first time it opens, the position of the tooltip is incorrect. After that, it's ok"

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.

"The position of the tooltip is consistently incorrect"

If the error still occurs, please open an issue on GitHub.

"Shouldn't Tooltipster remove <script> tags from my content to prevent XSS exploits?"

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.

"Tooltipster does not work with disabled <input> and <button> elements"

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.

"How compatible is Tooltipster with old versions of Internet Explorer ?"

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.

适用浏览器:360、FireFox、Chrome、Safari、Opera、傲游、搜狗、世界之窗. 不支持IE8及以下浏览器。

来源:懒人素材