Back to Tippyjs

HTML Content

website/src/pages/v5/html-content.mdx

6.3.71.9 KB
Original Source

The content prop can accept a string, element, or function.

To interact with the content inside the tippy, set interactive: true.

String

js
tippy('button', {
  content: '<strong>Bolded content</strong>',
});

Note

Ensure HTML strings containing user data are sanitized properly to prevent XSS attacks.

Element.innerHTML

You can pass in an element's .innerHTML string:

<!-- prettier-ignore -->
html
<div id="template" style="display: none;">
  <strong>Bolded content</strong>
</div>
js
const template = document.getElementById('template');

tippy('button', {
  content: template.innerHTML,
});

Element

You can pass the element itself, which is useful for keeping event listeners attached (or when a framework is controlling elements inside):

js
const template = document.getElementById('example');
template.style.display = 'block';

tippy(singleButton, {
  content: template,
});

This differs from passing a string in that a single element can only exist in a single tippy. The template will be moved from the document and into the tippy itself.

Template linking

If you have multiple references each with their own unique template, there is a way to link them with their associated template:

html
<button data-template="one">One</button>
<button data-template="two">Two</button>
<button data-template="three">Three</button>

<div style="display: none;">
  <div id="one">
    <strong>Content for `one`</strong>
  </div>
  <div id="two">
    <strong>Content for `two`</strong>
  </div>
  <div id="three">
    <strong>Content for `three`</strong>
  </div>
</div>

We can make content a function that receives the reference element (button in this case) and returns template content:

js
tippy('button', {
  content(reference) {
    const id = reference.getAttribute('data-template');
    const template = document.getElementById(id);
    return template.innerHTML;
  },
});