DEV Community

M. E. Patterson
M. E. Patterson

Posted on

8 4

Using Tippy.js with StimulusReflex and CableReady

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!)

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (1)

Collapse
 
leastbad profile image
  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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay