Skip to content

Instantly share code, notes, and snippets.

@razvanstatescu
Created August 7, 2020 16:49
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 razvanstatescu/f3db88f102a371b7c3139077a2c15201 to your computer and use it in GitHub Desktop.
Save razvanstatescu/f3db88f102a371b7c3139077a2c15201 to your computer and use it in GitHub Desktop.
Copy input text to clipboard using Javascript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Copy to clipboard</title>
<link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<style>
body {
background-color: #FAFAFA;
}
button {
color: #1D343E;
transition: .5s opacity;
}
button:hover {
opacity: .85;
}
input {
background-color: #B9E3C6;
color: #1D343E;
}
</style>
</head>
<body class="flex justify-center items-center h-screen">
<div>
<input id="text" type="text" class="h-10 rounded mr-4 w-64 outline-none px-4 cursor-not-allowed" value="https://example.com" readonly>
<button id="btn" class="text-xs font-bold uppercase"><i class="fa fa-clone"></i> copy link</button>
</div>
<script>
// Select button element
const btn = document.getElementById("btn");
// Select text input element
const text = document.getElementById('text');
// When button is pressed
btn.addEventListener('click', () => {
// Select the input text content
text.focus();
text.select();
// Copy content to clipboard
document.execCommand('copy');
// Remember the button current text
const oldText = btn.innerHTML;
// Set the button text to 'copied'
btn.innerHTML = '<i class="fa fa-check"></i> copied';
btn.classList.toggle('cursor-default');
// After 2s change it back
setTimeout(() => {
btn.innerHTML = oldText;
btn.classList.toggle('cursor-default');
}, 2000);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment