Skip to content

Instantly share code, notes, and snippets.

@guest271314
Created March 10, 2019 07:19
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 guest271314/7a58b1c33c40a92d1e6fc56940ae814c to your computer and use it in GitHub Desktop.
Save guest271314/7a58b1c33c40a92d1e6fc56940ae814c to your computer and use it in GitHub Desktop.
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