So I've read this entire post on how to copy text to a clipboard, and none of it seems to match what I'm looking for. How do I copy to the clipboard in JavaScript?
The program has several fields that are going to have text entered into them, that will then be copied and dropped into several other applications. I found a quick way to do this in IE, but it won't work in any other browser. Here's the HTML.
<SPAN ID="copytext" STYLE="height:150;width:162;background-color:pink">
This text will be copied onto the clipboard when you click the button below. Try it!
</SPAN>
<TEXTAREA ID="holdtext" STYLE="display:none;">
</TEXTAREA>
<BUTTON onClick="ClipBoard();">Copy to Clipboard</BUTTON>
And then here's the JavaScript.
<SCRIPT LANGUAGE="JavaScript">
function ClipBoard()
{
holdtext.innerText = copytext.innerText;
Copied = holdtext.createTextRange();
Copied.execCommand("Copy");
}
</SCRIPT>
The program can't have something like Zero Clipboard or Clippy, because it still needs to work if I put it on a different computer without those libraries. The best shot I've had was one on the link posted at the top of this article. It uses jQuery.
var copyTextareaBtn = document.querySelector('.js-textareacopybtn');
copyTextareaBtn.addEventListener('click', function(event) {
var copyTextarea = document.querySelector('.js-copytextarea');
copyTextarea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copying text command was ' + msg);
} catch (err) {
console.log('Oops, unable to copy');}});
So that works great for one field, but everything I've ever learned about programming tells me not to repeat myself over and over again. ESPECIALLY if I'm only changing one thing every time I repeat it. Is there a better way to do this? Or is jQuery and repetition my only option at this point?