Edit : the solution given by simone works, but it is in javascript, and as I already coded everything else in jquery, I ‘d love a jquery solution..
I have a series of divs widht content to copy. Looking at different examples, I decide to put a div with the content to copy, and just after that a hidden copy button. I wrap everything in a div in relative position, so that I can put the button in absolute position in the top right corner, exactly like this example.
Here is an example of my code:
<div class="token-block">
<div class="token" id="copy-1">{{customText[<span id="custom_wrapper">
<span class="output"></span><span class="output"></span></span>]}}</div>
<button type="button" class="copy" onclick="copy('#copy-1')" aria-hidden="false" aria-label="Copy to clipboard"><span class="visually-hidden">Copy to Clipboard</span></button>
</div>
</div>
The copy function works perfectly with this :
function copy(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(element).text()).select();
document.execCommand("copy");
$temp.remove();
}
But I’d prefer to have a dynamic solution. So I add the wrapping div, the id and copy button dynamically.
$(function() {
....
$('.token').wrap('<div class="token-block"></div>');
$('.token').each(function(){
i=0;
$(this).attr('id', 'token-'+i+'');
$(this).append('<button type="button" class="copy" onclick="copy(#copy-'+i+'")" aria-hidden="false" aria-label="Copy to clipboard"><span class="visually-hidden">Copy to Clipboard</span></button>');
i++;
});
});
function copy(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(element).text()).select();
document.execCommand("copy");
$temp.remove();
}
It doen’t work..So What is wrong here ? the code when I inspect the element is exactly the same in the html, but if I do it dynamicaly, it doesn’t work anymore..
can someone help please ??
2
Answers
EDIT : ok finaly I found a solution, in jquery, with dynamicaly added elements. Simone's solution below is cleaner, and she gives javascript and jquery solution.
To add wrapping div, and the hidden button :
And in the copy function, I can now target the right element to copy
I propose you a pure JS solution because clipboard used that like: