Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@w3collective w3collective commented Jun 21, 2021

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