Created
March 10, 2019 07:19
-
-
Save guest271314/7a58b1c33c40a92d1e6fc56940ae814c to your computer and use it in GitHub Desktop.
Javascript - copy text string on click
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
<!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