Tutorial
The short-form tutorial below represents how to pair Rails UI, Stimulus.js, and Tippy.js together.
1. Initializing the Stimulus.js controller
The Hound theme ships with the tooltip_controller.js controller file by default. Below is the file for reference. Tippy.js is required to make the tooltip component function properly. You may customize Tippy to your needs but we started of with some simple defaults.
import { Controller } from "@hotwired/stimulus"
import tippy from "tippy.js"
export default class extends Controller {
static values = {
content: String,
allowHtml: Boolean
}
connect() {
let options = {}
if (this.hasContentValue) {
options["content"] = this.contentValue
}
if (this.hasAllowHtmlValue) {
options["allowHTML"] = this.allowHtmlValue
}
this.tippy = tippy(this.element, options)
}
disconnect() {
this.tippy.destroy()
}
}
2. Initialize the controller in your views
Add the data attribute data-controller='tooltip' to an HTML element.
<button data-controller="tooltip" class="btn btn-primary">Tooltip demo</button>
3. Pass content to the tooltip
Add the data attribute data-tooltip-content-value='Your content here' to an HTML element. Inside the data attribute you may pass as much copy as you like.
<button data-controller="tooltip" data-tooltip-content-value="This is the content inside my tooltip!" class="btn btn-primary">Tooltip demo</button>
(optional) 4. Allow HTML in content
Add the data attribute data-tooltip-allow-html-value="true" to an HTML element. Inside the data attribute pass true to enable the option allowHTML for the tippy.js library.
<button data-controller="tooltip" data-tooltip-content-value="This is the <strong>bold</strong> and <u>underlined</u> content inside my tooltip!" data-tooltip-allow-html-value="true" class="btn btn-primary">Tooltip with HTML demo</button>