I want to copy the text of a data attribute into clipboard. I took reference from this.
Here is my html code:-
<a class="text-info mr-2" href="javascript:void(0);" data-copy-to-clipboard="Hello World" onclick="coptToClipboard(this);"><i class="bx bx-copy me-1"></i></a>
This is my javascript code:-
function coptToClipboard(obj) {
var text = $(obj).attr('data-copy-to-clipboard');
document.execCommand('copy', false, text);
}
However the text isn’t getting copied. If I use alert(text);
in the same function, I am getting "Hello World" in the alert message.
How can I fix this?
2
Answers
The document.execCommand(‘copy’) approach is now considered obsolete and may not work in some modern browsers. Instead, you can use the newer Clipboard API for this purpose.
It seems like you’re using
jQuery
to retrieve the value of thedata-copy-to-clipboard
attribute, but you’re trying to execute thedocument.execCommand('copy', false, text);
command, which is not the correct way to copy text to the clipboard in modern browsers. Instead, you should use the Clipboard API.