Further to this question: Copy to clipboard with jQuery/js in Chrome
The code from the above question works perfectly for copying a string to clipboard with JavaScript, but I need to trigger the process from a user click onto an injected element. For some reason, the code will not work if the element is injected.
In below code example, I added a red ?
button and prepended it to the body. Note that clicking on it does not copy the desired text to clipboard. Why is that?
(Note that I added my bit in jQuery as a personal preference)
var elem = document.getElementById('test');
var elem2 = document.getElementById('test2');
var elem3 = document.getElementById('test3');
elem.onmouseup = function () {
document.execCommand('copy');
}
elem2.addEventListener('copy', function (e) {
e.preventDefault();
if (e.clipboardData) {
e.clipboardData.setData('text/plain', 'custom content');
} else if (window.clipboardData) {
window.clipboardData.setData('Text', 'custom content');
}
});
elem3.onclick = function () {
document.execCommand('copy');
}
elem3.addEventListener('copy', function (e) {
e.preventDefault();
if (e.clipboardData) {
e.clipboardData.setData('text/plain', 'bonk custom contentt');
} else if (window.clipboardData) {
window.clipboardData.setData('Text', 'bonkcustom content from click');
}
});
$('body').prepend('<div id="test4" title="Click to copy text RAINBOX to clipboard">?</div>');
$(document).on('click', '#test4', function(e){
document.execCommand('copy');
});
$(document).on('copy', '#test4', function(e){
e.preventDefault();
if (e.clipboardData) {
e.clipboardData.setData('text/plain', 'Over the rainbox');
} else if (window.clipboardData) {
window.clipboardData.setData('Text', 'Rainbox');
}
});
#test4{display:inline-block;background-color:tomato;font-size:1.2rem;padding:0 5px;border-radius:3px;cursor:pointer;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div id='test'>Select text, it'll copy on mouse up</div>
<div id='test2'>Copy text using ctrl-c</div>
<div id='test3'>Click here to copy text</div>
<div id='ta'><textarea cols="40" rows="5" placeholder="Test pasting here"></textarea></div>