Created
June 21, 2021 04:58
-
-
Save w3collective/ab8f4a1143472cb7e88dfa25fc5cbf30 to your computer and use it in GitHub Desktop.
Copy text to the system clipboard on click with JavaScript
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 lang="en"> | |
<head> | |
<meta charset="UTF-8" /> | |
<meta name="viewport" content="width=device-width, initial-scale=1" /> | |
<title>JavaScript copy text to clipboard on click</title> | |
</head> | |
<body> | |
<label for="key-txt">Secret Key</label> | |
<input | |
type="text" | |
id="key-txt" | |
value="1seWYeywqmTnqv7a5FC6LkD2vsdEx6jXOwqkmhLN" | |
size="45" | |
readonly | |
/> | |
<button id="key-btn">COPY</button> | |
<script> | |
const keyTxt = document.getElementById("key-txt").value; | |
const keyBtn = document.getElementById("key-btn"); | |
keyBtn.addEventListener("click", async () => { | |
if (!navigator.clipboard) { | |
alert("Copy functionality not supported"); | |
} | |
try { | |
await navigator.clipboard.writeText(keyTxt); | |
} catch (err) { | |
console.error("ERROR", err); | |
} | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Source => https://w3collective.com/javascript-copy-clipboard/