Last active
May 27, 2024 05:03
-
-
Save chanakasan/d38ef69c1a97dd2a7c3f334e738b6f92 to your computer and use it in GitHub Desktop.
Stimulus - integrate with popper.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// app/javascript/controllers/index.js | |
import PopperController from "./popper_controller" | |
application.register("popper", PopperController) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// app/javascript/controllers/popper_controller.js | |
import { createPopper } from '@popperjs/core'; | |
import { Controller } from "@hotwired/stimulus" | |
export default class extends Controller { | |
connect() { | |
console.log("Popper connect! 123") | |
const el = this.element | |
const target = this.getTarget() | |
console.log(el) | |
console.log(target) | |
this.target = target | |
const showEvents = ['mouseenter', 'focus']; | |
const hideEvents = ['mouseleave', 'blur']; | |
showEvents.forEach((event) => { | |
el.addEventListener(event, () => this.show(target)); | |
}); | |
hideEvents.forEach((event) => { | |
el.addEventListener(event, () => this.hide(target)); | |
}); | |
this.popper = createPopper(el, target, { | |
placement: 'right', | |
modifiers: [ | |
{ | |
name: 'offset', | |
options: { | |
offset: [0, 8], | |
}, | |
}, | |
], | |
}); | |
} | |
disconnect() { | |
this.popper.destroy(); | |
} | |
getTarget() { | |
return document.querySelector(this.data.get("target")); | |
} | |
show(target) { | |
// const target = this.getTarget() | |
target.setAttribute('data-show', ''); | |
// We need to tell Popper to update the tooltip position | |
// after we show the tooltip, otherwise it will be incorrect | |
this.popper.update(); | |
} | |
hide(target) { | |
// const target = this.getTarget() | |
target.removeAttribute('data-show'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment