Copy to Clipboard with JavaScript
A nice feature is to let users automatically copy some text to their clipboard by clicking a button.
An example of where this can be helpful is when you need to get a URL to share with others.
Let’s see how we can do this in JavaScript.
First, we add an input field with the value we want to copy, and a button to trigger the copying:
<input type="text" class="text" value="magnusbenoni.com">
<button type="button" class="button">Copy text to clipboard</button>
Then we add the necessary JavaScript code:
const text = document.querySelector('.text');
const button = document.querySelector('.button');
button.onclick = function () {
// Select the text
text.select();
// Copy it
document.execCommand('copy');
// Remove focus from the input
text.blur();
};
We select the text in the input field, and use the execCommand()
function to copy the text to the clipboard. Then we remove focus from the input field.
It’s important to note that the execCommand()
function will only run as a result of a user action, such as a button click. This prevents you from messing with the users clipboard without them knowing it.
Take a look at the end result below. I also added a flashing message telling the user that the text was copied: