In a previous tutorial we saw how you can create a copy and paste button using jQuery and the ZeroClipboard flash
extension. The problem with this is that it requires flash. As most of the web is moving away from flash and some people
don't even have flash installed on their browser we need another solution. The reason flash was used to copy and paste
is mainly down to browser compatibility, now with most browsers now supporting the API to enable you to copy and paste
directly using Javascript using the Web API document.execCommand
. View the demo to see how the API works
HTML
First we add the HTML to the page we need a textbox to enter the content we want to copy, a button that will have the click event to start the copy process and a textarea where we can test the copy is successful by pasting the contents into it.
<div>
<input type="text" id="text-to-copy" placeholder="Enter text"/>
<button id="copy-text">Copy</button>
<span id="copied-text" style="display: none;">Copied!</span>
</div>
<div>
<textarea name="paste-area" id="paste-area" cols="30" rows="10" placeholder="Paste it here"></textarea>
</div>
Copy Text
To copy the text we first need to add a click event to the button.
document.getElementById('copy-text').addEventListener('click', function(e){
// Click event
});
Inside the click event we need to select the text inside the textbox.
document.getElementById('text-to-copy').select();
With the text selected we can now use the execCommand('copy')
to copy the text to the clipboard.
copied = document.execCommand('copy');
The return of this method will be a boolean on if the text was copied or not, you can then check this boolean value to display a message if it was able to be copied.
// Add click event
document.getElementById('copy-text').addEventListener('click', function(e){
e.preventDefault();
// Select the text
document.getElementById('text-to-copy').select();
var copied;
try
{
// Copy the text
copied = document.execCommand('copy');
} catch (ex) {
copied = false;
}
if(copied) {
// Display the copied text message
document.getElementById('copied-text').style.display = 'block';
}
});