I need a bit of help. I'm modifying one of my projects. Currently there is a button that a user can click on to copy the text contents of a div to the clip board.
function copyToClipboard(element) {
var $temp = $("<textarea>");
var brRegex = /<br\s*[\/]?>/gi;
$("body").append($temp);
$temp.val($(element).html().replace(/<\/?[a-zA-Z]+\/?>/g, '').trim()).select();
document.execCommand("copy");
$temp.remove();
}
and I have a button that's set up as below
<button style="copy-button" onclick="copyToClipboard('#copytarget')" id="copyresults">Copy to Clipboard</button>
I'm now trying to modify this code, so that rather than clicking on the button, a user can just click the text itself (a div with an id of 'copytarget') to copy it to the clipboard, but I'm having problems making it work. I've got the below, but it's not copying!
document.getElementById("copytarget").addEventListener("click", copyToClipboard);
function copyToClipboard() {
var $temp = $("<textarea>");
var brRegex = /<br\s*[\/]?>/gi;
$("body").append($temp);
$temp.val($(element).html().replace(/<\/?[a-zA-Z]+\/?>/g, '').trim()).select();
document.execCommand("copy");
$temp.remove();
}
Can anyone see what I'm doing wrong? Thanks in advance!
You just need to select the copytarget
again - easiest to just select it once, and then refer to that variable when you add the listener and when you grab its val
. Currently, you haven't assigned copytarget
to your element
:
const copytarget = document.getElementById("copytarget");
copytarget.addEventListener("click", copyToClipboard);
function copyToClipboard() {
var $temp = $("<textarea>");
var brRegex = /<br\s*[\/]?>/gi;
$("body").append($temp);
$temp.val($(copytarget).html().replace(/<\/?[a-zA-Z]+\/?>/g, '').trim()).select();
document.execCommand("copy");
$temp.remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="copytarget">copy here</div>
But there's no need to include a big library like jQuery just for this:
const copytarget = document.getElementById("copytarget");
copytarget.addEventListener("click", copyToClipboard);
function copyToClipboard() {
const temp = document.body.appendChild(document.createElement('textarea'));
temp.value = copytarget.textContent.replace(/<\/?[a-zA-Z]+\/?>/g, '').trim();
temp.select();
document.execCommand("copy");
temp.remove();
}
<div id="copytarget">copy here 2</div>