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


i want have button selects text in textarea , copies clipboard. can't seem find solutions work in browsers , don't use flash.

surely doable? i've seen on place guess use flash, want stay away if possible people don't have it.

this have far - selects text:

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

(the focus not strictly necessary)

execcommand('copy')

there new option. cross-browser take time until has updated browser.

it works using document.execcommand('copy'); function. function you'll copy select text. not work textareas every selected text on webpage (like in span, p, div, etc.).

available in internet explorer 10+, chrome 43+, opera 29+ , firefox 41+ (see execcommand compatibility here).

example

// setup variables  var textarea = document.getelementbyid("textarea");  var answer  = document.getelementbyid("copyanswer");  var copy    = document.getelementbyid("copyblock");  copy.addeventlistener('click', function(e) {       // select text (you create range)     textarea.select();        // use try & catch unsupported browser     try {           // important part (copy selected text)         var ok = document.execcommand('copy');           if (ok) answer.innerhtml = 'copied!';         else    answer.innerhtml = 'unable 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 copy</button> <span id="copyanswer"></span>     


Comments

Popular posts from this blog

java - Jmockit String final length method mocking Issue -

asp.net - Razor Page Hosted on IIS 6 Fails Every Morning -

c++ - wxwidget compiling on windows command prompt -