Search code examples
javascriptbuttoncopyselection

How to copy a button text?


I want to copy the text from a button when I click on it. I reused code from w3 schools. The difference with the w3 schools code is that when you click on a button it copy the text from an input, I want to copy the text from the button I'm clicking on.

function copyClipboard() {
  var copyText = document.getElementById("myButton").innerHTML;
  document.execCommand("copy");
}
<button id="myButton" onclick="copyClipboard()">Text I want to copy</button>

When I console.log copyText it display the text from the button but my text is never copied.

Do you know why ?


Solution

  • Your problem is that you are only storing the value of the button, but you are selecting nothing, so nothing will be copied to clipboard.

    You need to put that content in an input and select its value using .select(), so it can be copied:

    function copyClipboard() {
      var copyText = document.getElementById("myButton").innerHTML;
      
      var input = document.createElement("input");
      input.value = copyText;
      document.body.appendChild(input);
      input.select();
      document.execCommand("copy");
      document.body.removeChild(input); 
    }
    <button id="myButton" onclick="copyClipboard()">Text I want to copy</button>