Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy selected text to the clipboard WITHOUT using flash - must be cross-browser

I want to have a button which selects the text in a textarea and copies it to the clipboard. I can't seem to find any solutions which work in all browsers and don't use flash.

Surely this is doable? I've seen it all over the place but I guess they use flash, which I really want to stay away from if possible as some people don't have it.

This is what I have so far - it just selects the text:

function copyCode() {   $("#output-code").focus();   $("#output-code").select(); } 

(The focus is not strictly necessary)

like image 804
Nick Brunt Avatar asked Jun 09 '11 22:06

Nick Brunt


People also ask

How do I copy text to the clipboard?

Copying Text to the ClipboardCTRL+C to copy. CTRL+X to cut. CTRL+V to paste.

What does it mean to copy to clipboard?

Android can cut, copy and paste text, and like a computer, the operating system transfers the data to the clipboard. Unless you use an app or extension like Clipper or aNdClip to retain your clipboard history, however, once you copy new data to the clipboard, the old information is lost.


1 Answers

execCommand('copy')

There is a very new option. It is cross-browser but it will take time until everyone has updated their browser.

It works by using the document.execCommand('copy'); function. With this function you'll copy the select text. This will not only work with textareas but with every selected text on the webpage (like in span, p, div, etc.).

Available in Internet Explorer 10+, Chrome 43+, Opera 29+ and Firefox 41+ (see execCommand compatibility here).

Example

// Setup the variables  var textarea = document.getElementById("textarea");  var answer  = document.getElementById("copyAnswer");  var copy    = document.getElementById("copyBlock");  copy.addEventListener('click', function(e) {       // Select some text (you could also create a range)     textarea.select();        // Use try & catch for unsupported browser     try {           // The important part (copy selected text)         var ok = document.execCommand('copy');           if (ok) answer.innerHTML = 'Copied!';         else    answer.innerHTML = 'Unable to copy!';     } catch (err) {         answer.innerHTML = 'Unsupported Browser!';     }  });
<textarea id="textarea" rows="6" cols="40">  Lorem ipsum dolor sit amet, eamsemper maiestatis no.  </textarea><br/>    <button id="copyBlock">Click to copy</button> <span id="copyAnswer"></span>     
like image 111
arc Avatar answered Sep 28 '22 06:09

arc