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:
delegate
to the html
element, which is present while the javascript is being parsed. It will then make tippy work for all elements with either the data attribute data-tippy-content
or alternatively the data-tippy-template
attribute (as seen in the target
-property).content
-method (instead of a property) to the configuration, which uses the data-tippy-template
attribute to present the content. We have to check for the existence of a template id-reference, as at first run it tries to get the data-tippy-template
from the html
-tag.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.
Enjoyed this? Follow me on Mastodon or add the RSS, euh ATOM feed to your feed reader.
Dit artikel van murblog van Maarten Brouwers (murb) is in licentie gegeven volgens een Creative Commons Naamsvermelding 3.0 Nederland licentie .