Skip to content

Instantly share code, notes, and snippets.

@jmarsh24
Created February 19, 2022 14:40
Show Gist options
  • Save jmarsh24/3c844372a390c183fbe996b18918f1d5 to your computer and use it in GitHub Desktop.
Save jmarsh24/3c844372a390c183fbe996b18918f1d5 to your computer and use it in GitHub Desktop.
import { Controller } from "stimulus";
import { createPopper } from "@popperjs/core";
export default class extends Controller {
static targets = ["element", "tooltip"];
static values = {
placement: String,
offset: Array
};
initialize() {
this.placementValue = "top"
this.offsetValue = [0, 8]
}
connect() {
// Create a new Popper instance
this.popperInstance = createPopper(this.elementTarget, this.tooltipTarget, {
placement: this.placementValue,
modifiers: [
{
name: "offset",
options: {
offset: this.offsetValue,
},
},
],
});
}
show(event) {
this.tooltipTarget.setAttribute("data-show", "");
// We need to tell Popper to update the tooltip position
// after we show the tooltip, otherwise it will be incorrect
this.popperInstance.update();
}
hide(event) {
this.tooltipTarget.removeAttribute("data-show");
}
// Destroy the Popper instance
disconnect() {
if (this.popperInstance) {
this.popperInstance.destroy();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment