I have list of images. I want to copy data attribute on click to clipboard. What I have now is alert data-attribute. I tried copy command but it didn't work (don't copy anything). Please, can anyone help me with that?
var emojiImages = document.getElementsByClassName('emoji-image');
for(var i=0; i< emojiImages.length; i++){
emojiImages[i].onclick = function(){
var a = this.getAttribute('data-emoji');
alert(a);
}
}
<ul style="display: block; column-count: 8;"><li>:first:<img class="emoji-image" src="https://www.gravatar.com/avatar/086495a58faa8219a2640ad87325a12d?s=48&d=identicon&r=PG&f=1" width="36" height="36" data-emoji=":first:"></li><li>:second:<img class="emoji-image" src="https://www.gravatar.com/avatar/086495a58faa8219a2640ad87325a12d?s=48&d=identicon&r=PG&f=1" width="36" height="36" data-emoji=":second:"></li></ul>
The Idea that copy command works great if there is a textarea or input element visible on screen.
so create one put text in it, copy textarea content, then remove it.
var emojiImages = document.getElementsByClassName('emoji-image');
for(var i=0; i< emojiImages.length; i++){
emojiImages[i].onclick = function(){
var a = this.getAttribute('data-emoji');
var textArea = document.createElement("textarea");
textArea.value = a;
document.body.appendChild(textArea);
textArea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
} catch (err) {
console.log('Oops, unable to copy');
}
document.body.removeChild(textArea);
}
}
<ul style="display: block; column-count: 8;"><li>:first:<img class="emoji-image" src="https://www.gravatar.com/avatar/086495a58faa8219a2640ad87325a12d?s=48&d=identicon&r=PG&f=1" width="36" height="36" data-emoji=":first:"></li><li>:second:<img class="emoji-image" src="https://www.gravatar.com/avatar/086495a58faa8219a2640ad87325a12d?s=48&d=identicon&r=PG&f=1" width="36" height="36" data-emoji=":second:"></li></ul>
check accepted answer here , copy action is explained in more details.