loading...

Using Tippy.js with StimulusReflex and CableReady

mepatterson profile image M. E. Patterson ・2 min read

So you've got a killer StimulusReflex-based Rails app going, and you're using CableReady all over the place, and the DOM is morphing, and everything is going great! Now, you're ready to start adding in some tooltips here and there to polish up your user experience. Enter Tippy.js for much success.

At first, you just add an event handler listening to turbolinks reloads and have it initialize all the tippy elements on the page. And that works great...

...until you use a Reflex to morph the DOM. Ack! Elements that were morphed that were supposed to have Tippy(s) now... don't.

Of course, this makes sense. StimulusReflex, via CableReady, is morphing the DOM; it's not a Turbolinks load. So we'll need to change that.

First, get rid of the turbolinks event handler. We're just going to do this with Stimulus and a cable-ready:after-morph event handler:

// tippy_controller.js

import { Controller } from "stimulus";
import tippy from "tippy.js";

export default class extends Controller {
  initialize() {
    document.addEventListener(
      "cable-ready:after-morph",
      this.initializeTippys.bind(this),
      true
    );
  }

  connect() {
    this.initializeTippys();
  }

  disconnect() {
    this.destroyTippys();
  }

  initializeTippys() {
    this.destroyTippys();
    tippy(document.querySelectorAll("[data-tippy-content]"));
  }

  destroyTippys() {
    let tips = document.querySelectorAll("[data-tippy-content]");
    tips.forEach((e) => {
      if (e._tippy) e._tippy.destroy();
    });
  }
}

Cool. Now that that's out of the way, you just need to add data-controller="tippy" to the right element(s) in your HTML. Personally, I just add it to the BODY tag so I can always make tooltips anywhere, any time.

Enjoy!

(let me know in the comments if there's an issue with this approach, or you have a better way, but it worked for me!)

Posted on by:

mepatterson profile

M. E. Patterson

@mepatterson

Building web apps for 20 years. Mostly Ruby and JS. Lots of SQL. Specialist in data architectures and cocktails.

Discussion

markdown guide
 
  1. I know this is obnoxious but... don't you mean tippies

  2. You should take something like stimulus-shortcut, replace all of the bits and bobs, and then publish this as stimulus-tippies