I am trying to copy the text from inside an Ace Editor box into my local clipboard, using the pure JS method described here. However, when I click my copy button, it will throw me an error:
"TypeError: copyTextarea.select is not a function"
and the text will not copy to my clipboard. Is there a way to do this somehow (either pure JS or jQuery)? My code is as follows (simplified but should be enough):
$('#clipboard').on('click', function() {
var copyTextarea = document.querySelector('#result-box');
copyTextarea.select();
document.execCommand('copy');
});
<button id="clipboard">Copy</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result-box" style="height: 100px; width: 100%; border-radius: 4px; border: 1px solid #DDD;"><!DOCTYPE html>
<html>
</html></div>
<script src="https://cdn.rawgit.com/ajaxorg/ace-builds/master/src-noconflict/ace.js" type="text/javascript" charset="utf-8"></script>
<script>
var editor = ace.edit("result-box");
editor.getSession().setMode("ace/mode/html");
editor.setReadOnly(true);
editor.setShowPrintMargin(false);
editor.getSession().setUseWrapMode(true);
</script>
P.S.: There is another error thrown about some worker and whatnot concerning Ace, if anyone knows how to fix that, too, comment below. Thanks in advance!
call focus and selectAll on the editor, it works on most of modern browsers
$('#clipboard').on('click', function() {
var sel = editor.selection.toJSON(); // save selection
editor.selectAll();
editor.focus();
document.execCommand('copy');
editor.selection.fromJSON(sel); // restore selection
});
<button id="clipboard">Copy</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result-box" style="height: 100px; width: 100%; border-radius: 4px; border: 1px solid #DDD;"><!DOCTYPE html>
<html>
</html></div>
<script src="https://cdn.rawgit.com/ajaxorg/ace-builds/master/src-noconflict/ace.js" type="text/javascript" charset="utf-8"></script>
<script>
var editor = ace.edit("result-box");
editor.getSession().setMode("ace/mode/html");
editor.setReadOnly(true);
editor.setShowPrintMargin(false);
editor.getSession().setUseWrapMode(true);
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With