Skip to content

Instantly share code, notes, and snippets.

@s-aska
Last active July 20, 2023 17:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save s-aska/cd9daba1637a9aa1030f8d8a2e7c169e to your computer and use it in GitHub Desktop.
Save s-aska/cd9daba1637a9aa1030f8d8a2e7c169e to your computer and use it in GitHub Desktop.
もう addEventListener しなくて良い...!!
<div data-controller="clipboard">
<button data-action="click->clipboard#copy" type="button" data-clipboard-target="value" data-copy="some copy text"></button>
<div data-clipboard-target="tooltip" role="tooltip" class="absolute z-10 invisible inline-block px-3 py-2 text-sm font-medium text-white transition-opacity duration-300 bg-gray-900 rounded-lg shadow-sm opacity-0 tooltip dark:bg-gray-700">
Copied!
<div class="tooltip-arrow" data-popper-arrow></div>
</div>
</div>
declare global {
interface Window {
Stimulus: any
}
}
import { Application } from "@hotwired/stimulus"
import ClipboardController from './controllers/clipboard_controller'
window.Stimulus = Application.start()
window.Stimulus.register("clipboard", ClipboardController)
import { Controller, Context } from '@hotwired/stimulus'
import { Tooltip } from 'flowbite';
export default class ClipboardController extends Controller {
static targets = [ 'value', 'tooltip' ]
declare readonly valueTarget: HTMLInputElement
declare readonly tooltipTarget: HTMLElement
declare readonly tooltip: Tooltip
constructor(context: Context) {
super(context)
this.tooltip = new Tooltip(this.tooltipTarget, this.valueTarget, {
placement: 'top',
triggerType: 'none',
})
}
copy() {
navigator.clipboard.writeText(this.value).then(() => {
this.tooltip.show();
setTimeout(function () {
this.tooltip.hide();
}, 1000);
});
}
get value() {
return this.valueTarget.dataset.copy
}
}
// 移行前のコード
import { documentReady } from 'html-ready';
import { Tooltip } from 'flowbite';
documentReady.then(() => {
document.querySelectorAll(".js-text-copy").forEach((element: HTMLInputElement) => {
const text = element.dataset.copy;
const target = document.getElementById(element.dataset.target);
const tooltip = new Tooltip(target, element, {
placement: 'top',
triggerType: 'none',
});
element.addEventListener("click", (e) => {
navigator.clipboard.writeText(text).then(() => {
tooltip.show();
setTimeout(function () {
tooltip.hide();
}, 1000);
});
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment