Copy text to clipboard using jQuery

In most common way, we are using (ctrl + C) keys together on keyboard to copy text to clipboard. But what if we want to implement this feature on button click? So we can do this using JavaScript/jQuery. JavaScript provides the easiest way to achieve this task. To copy content JavaScript provides execCommand() method on HTML Dom to copy content of specific selectors.

The proper use of execCommand() method like this 

document.execCommand("copy"); , we have to pass one parameter to this method and this parameter is called command that we want to perform using this method. JavaScript provides different commands for specific actions and I have provided list below of all commands.

Commands for execCommand() :

These are names of commands that executes on selected text :

“backColor”“bold”
“createLink”“copy”
“cut”“defaultParagraphSeparator”
“delete”“fontName”
“fontSize”“foreColor”
“formatBlock”“forwardDelete”
“insertHorizontalRule”“insertHTML”
“insertImage”“insertLineBreak”
“insertOrderedList”“insertParagraph”
“insertText”“insertUnorderedList”
“justifyCenter”“justifyFull”
“justifyLeft”“justifyRight”
“outdent”“paste”
“redo”“selectAll”
“strikethrough”“styleWithCss”
“subscript”“superscript”
“undo”“unlink”
“useCSS”

Code snippet to use this commands :

We can use “copy” command in execCommand() method to copy content. The following code snippet is copy text from text-area to clipboard on click of button using execCommand and jQuery/JavaScript.

HTML :

<div>
    <textarea id="description">
        Copy text to clipboard using jQuery - All commands and code snippet provided
    </textarea>
    <button id="copy_btn">Copy Content</button>
</div>

jQuery/Javascript :

<script>
    jQuery("#copy_btn").click(function ($) {
        var textarea = jQuery("#description");
        textarea.select();
        document.execCommand("copy");
        alert("Copied the text: " + textarea.val());
    });
</script>

Conclusion :

As you can see, to copy text to clipboard using jQuery is not so difficult. JavaScript has provided method and some commands to get this task done. In future post we will see some more methods provided by jQuery. So stay connected with my blog to get useful stuff in simple manner, and I will be more happy to get some feedback from you in comment section, and also share this post if its useful for others. Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.