I want to make the "COPY ADDRESS" button copy a text I specify. I already tried to do it myself, but couldn't do it. It is very simple, I just have minimal knowledge.
<a class="btn btn-lg" href="#">copy address</a>
I want to make the "COPY ADDRESS" button copy a text I specify. I already tried to do it myself, but couldn't do it. It is very simple, I just have minimal knowledge.
<a class="btn btn-lg" href="#">copy address</a>
This code will copy the text abc
to the clipboard.
function copy(text) {
document.body.insertAdjacentHTML("beforeend","<div id=\"copy\" contenteditable>"+text+"</div>")
document.getElementById("copy").focus();
document.execCommand("selectAll");
document.execCommand("copy");
document.getElementById("copy").remove();
}
<button onclick="copy('abc')">Copy</button>
contenteditable
div with the id of copy
(don't use this ID anywhere else on your page). contenteditable
elements are elements which are designed to be edited by the user, and there is extensive native JavaScript around them in the form of document.execCommand
provided to help people make rich text editors. Part of document.execCommand
is a copy
method, to add text to the clipboard - however this only works reliably with selected text in a contenteditable
element.document.execCommand
to select all of the text inside of the contenteditable
div. In the first step, we ensured that this text was the text passed to the function. document.execCommand("copy")
. This is actually surprisingly simple.These actions should all happen so fast that the user will not realise that a div has even been created, however the text will appear on their clipboard.