Skip to content

Instantly share code, notes, and snippets.

@w3collective
Created June 21, 2021 04:58
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 w3collective/ab8f4a1143472cb7e88dfa25fc5cbf30 to your computer and use it in GitHub Desktop.
Save w3collective/ab8f4a1143472cb7e88dfa25fc5cbf30 to your computer and use it in GitHub Desktop.
Copy text to the system clipboard on click with JavaScript
<!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>
@w3collective
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment