Copy Selected Text in JavaScript


/ Published in: JavaScript
Save to your folder(s)

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:


Copy this code and paste it in your HTML
  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>
  20.  
  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>

URL: http://www.apphp.com/index.php?snippet=javascript-copy-selected-text

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.