2


I am looking for a javascript function which can copy contents from TextArea into clipboard. On microsoft platform the function works fine, but it fails when I switch to non-microsoft platform such as, FireFox or Safari.
I referred this link for the function.


If anyone knows the solution for this, please help me out.
Thanks in advance.

cweiske
  • 30,033
  • 14
  • 133
  • 194
VJOY
  • 3,752
  • 12
  • 57
  • 90
  • Duplicate of: http://stackoverflow.com/questions/127040/copy-put-text-on-the-clipboard-with-firefox-safari-and-chrome and http://stackoverflow.com/questions/2072026/copy-to-clipboard-not-working-on-firefox – RoToRa Aug 06 '10 at 08:59
  • but the solutions which are provided and accepted for these questions, doesn't work. So I thought to re-post it to get better solutions. – VJOY Aug 07 '10 at 10:43

1 Answers1

0

A pure JavaScript solution for copying the contents of a textarea to the clipboard when the user clicks on the textarea:

<script>

function copySelectionText(){
    var copysuccess // var to check whether execCommand successfully executed
    try{
        copysuccess = document.execCommand("copy") // run command to copy selected text to clipboard
    } catch(e){
        copysuccess = false
    }
    return copysuccess
}

function copyfieldvalue(e, id){
    var field = document.getElementById(id)
    field.select()
    var copysuccess = copySelectionText()
}

var bio = document.getElementById('mybio')
bio.addEventListener('mouseup', function(e){
    copyfieldvalue(e, 'mybio')
    var copysuccess = copySelectionText() // copy user selected text to clipboard
}, false)

</script>

Note: If you want to copy only parts of the textarea contents to clipboard, the tutorial Reading and copying selected text to clipboard using JavaScript has more info on that.

coco puffs
  • 1,040
  • 12
  • 8