Copy Selected Text in JavaScript

Sometimes you have some information on your page and your visitors might want to copy it. The easiest way is to provide a mechanism that allows them to simply click a button to do so. You have to paste this code into the head of your web page:

[View All Snippets]
Show Plain Text »
  1. <script language="javascript">
  2. function CopyText(el){
  3.     var selectedText = "";
  4.     if(window.getSelection){
  5.         selectedText = window.getSelection();
  6.     }else if(document.getSelection){
  7.         selectedText = document.getSelection();
  8.     }else if(document.selection){
  9.         selectedText = document.selection.createRange().text;
  10.     }
  11.     if(selectedText != ""){
  12.         selectedText = selectedText.toString();
  13.         el.focus();
  14.         el.value = selectedText;
  15.     }else{
  16.         alert("Select a text in the page and then press this button!");
  17.     }
  18. }
  19. </script>
  21. Select any part of this text to copy it...
  22. <form name="frmCopyText">
  23. <textarea name="txtSelect" rows="4" cols="45"></textarea><br>
  24. <input onclick="CopyText(this.form.txtSelect)"
  25.        type="button"
  26.        value="Press to copy the highlighted text"
  27.        name="btnCopy">
  28. </form>
Create Your Free Account
Please remember that this information is essential to use our services correctly.
After creating the account you will be able to download all of our FREE products.
Fields marked with * are mandatory

Please send me information about updates, new products, specials and discounts from ApPHP!
We recommend that your password should be at least 6 characters long and should be different from your username/email. Please use only letters of the English alphabet to enter your name.

Your e-mail address must be valid. We use e-mail for communication purposes (order notifications, etc). Therefore, it is essential to provide a valid e-mail address to be able to use our services correctly.

All your private data is confidential. We will never sell, exchange or market it in any way. Please refer to Privacy Policy.

By clicking "Create Account", you are indicating that you have read and agree to the ApPHP Terms & Conditions.

Quick Registration with: Facebook / Google