Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Javascript - copy text string on click
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<span>text</span>
<button>click</button>
<div>other text</div>
<script>
// How do I get a hold of clipboardData without a copy event?
// As in from another event handler, like a click event on a separate element?
// The copy event is not firing. – Chloe May 12 '18 at 20:21
// https://stackoverflow.com/questions/45071353/javascript-copy-text-string-on-click/45071478#comment87636636_45071478
const dt = new DataTransfer();
const span = document.querySelector("span");
const button = document.querySelector("button");
span.addEventListener("click", e => {
document.execCommand("copy");
});
button.addEventListener("click", e => {
console.log(dt.getData("text"), dt.items);
});
document.addEventListener("copy", e => {
e.preventDefault();
e.clipboardData.setData("text", e.target.textContent);
dt.setData("text", e.clipboardData.getData("text"));
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.