Creating Tooltips
Call the tippy()
function by passing in a CSS selector, and give your
reference element(s) a data-tippy-content
attribute:
<button data-tippy-content="Tooltip">Text</button>
<button data-tippy-content="Another Tooltip">Text</button>
tippy('button')
The data-tippy-content
attribute allows you to give different tooltip content
to many different elements, while only needing to initialize once.
For single elements, you can use the content
option:
tippy('#singleElement', {
content: 'Tooltip',
})
Target types
The first argument you pass to tippy()
is the targets you want to give
tooltips to. This can represent one or many different elements.
// String: Any CSS selector is valid
tippy('#id')
tippy('.class')
tippy('[data-tippy-content]')
// Element | Element[]: An element or an array of elements is valid
const element = document.getElementById('my-element')
tippy(element)
tippy([element1, element2, element3])
// NodeList is valid
const els = document.querySelectorAll('.my-elements')
tippy(els)
Auto-initialization
If your web page has regular server-rendered HTML, and you aren't using a
front-end framework like React or Vue, then you can bypass the function call and
use the data-tippy
attribute:
<button data-tippy="I will be created automatically">Text</button>
Note the lack of -content
suffix.
This attribute should only be used for basic tippys that exist on the document on page load. You can avoid it if you want - it's just the quickest way to initialize a tooltip.
Client-rendered elements
Every time you create a new element with JavaScript, you should pass it to
tippy()
in order to apply a tooltip to it.
const strong = document.createElement('strong')
strong.textContent = 'reference'
document.body.appendChild(strong)
// `content` is the JavaScript form of the `data-tippy-content` HTML attribute
tippy(strong, { content: 'tooltip' })
Disabled elements
If an element is disabled, you will need to use a wrapper element (<span>
or
<div>
) in order for the tippy to work. Elements with the disabled attribute
aren't interactive, meaning users cannot focus, hover, or click them to trigger
a tippy.
<!-- Won't work! -->
<button data-tippy="Tooltip" disabled>Text</button>
<!-- Wrapper <span> will work -->
<span data-tippy="Tooltip">
<button disabled>Text</button>
</span>
⚠️ SVG in IE11
If you need to support SVG elements in IE11, you will need to include polyfills
for Element.prototype.classList
and SVGElement.prototype.contains
.
The easiest fix is to include these scripts in your document before Tippy's scripts:
<script src="https://polyfill.io/v3/polyfill.min.js?features=Element.prototype.classList"></script>
<script>
if (!SVGElement.prototype.contains) {
SVGElement.prototype.contains = HTMLDivElement.prototype.contains
}
</script>