Posted By

apphp-snippets on 02/13/13


Tagged

javascript text selected


Versions (?)

Copy Selected Text in JavaScript


 / Published in: JavaScript
 

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

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:

  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>

Report this snippet  

You need to login to post a comment.