Using Tippy.js with Turbolinks

An article, posted about 4 years ago filed in library, javascript, html & TurboLinks.

Tippy.js is a nice library to show popups. It may, however, not always be obvious how to use Tippy.js with Turbolinks (or any other library that modifies the DOM). The basic ingredient is somewhat hidden in the docs: deffered. But loading a HTML template requires a slight adaptation of what is presented in their documentation to make loading of these templates deferred.

From beginning to start. Add the library:

$ yarn add tippy.js

Add a CSS-class for your templates to be hidden by default:

.tippy-template-content {
  display: none;
}

And then add the following to your application.js (or equivalent in your setup):

import {delegate} from 'tippy.js';

delegate('html', {
  content(reference) {
    const id = reference.getAttribute('data-tippy-template');
    if (id) {
      const template = document.getElementById(id);
      return template.innerHTML;    
    }
  },
  allowHTML: true,
  target: "*[data-tippy-content],*[data-tippy-template]",
});

This does the following:

Our HTML can now look like this:

<button data-tippy-template="tippy-content-a3ffa">
<div id="tippy-content-a3ffa" class="tippy-template-content">
    <h3>Tippy content</h3>
    <p>With <strong>HTML</strong>!</p>
</div>

Further fine tuning can be done via the button’s data-attributes.

Op de hoogte blijven?

Maandelijks maak ik een selectie artikelen en zorg ik voor wat extra context bij de meer technische stukken. Schrijf je hieronder in:

Mailfrequentie = 1x per maand. Je privacy wordt serieus genomen: de mailinglijst bestaat alleen op onze servers.