Copy to Clipboard
Implement copy-to-clipboard with the modern Clipboard API and jQuery for click handling.
Implement copy-to-clipboard with the modern Clipboard API and jQuery for click handling.
$("[data-copy]").on("click", async function() {
const $btn = $(this);
const text = $($(this).data("copy")).text() || $(this).data("copy");
try {
await navigator.clipboard.writeText(text);
$btn.text("Copied!").addClass("btn-success");
setTimeout(() => $btn.text("Copy").removeClass("btn-success"), 2000);
} catch {
// Fallback: select and execCommand
const $tmp = $("<input>").val(text).appendTo("body").select();
document.execCommand("copy"); $tmp.remove();
$btn.text("Copied!"); setTimeout(() => $btn.text("Copy"), 2000);
}
});
Clipboard API requires HTTPS and user gesture — it works inside click handlers but not in arbitrary async code.