Skip to content

Copy text from textarea to clipboard – Python

I’m trying to enable a Copy button that will copy the content from the textarea, I gave an example of my HTML file and JS, I tried in all ways but I didn’t succeed. Thanks for your help.

My HTML

    {% if trans != "" %}
    <br>
        <div id="sTransContainer">
            <h1>Trans</h1>
            <textarea style="resize:none" cols="5" rows="10" id="sText">{{ trans }}</textarea>
            <div class="right btn-group">
                <button onclick="myFunction()">Copy text</button>
                <script async src="js/copy.js"></script>
            </div>
        </div>
    {% endif %}

My copy.js

function myFunction() {
  var copyText = document.getElementById("trans");
  copyText.select();
  copyText.setSelectionRange(0, 99999)
  document.execCommand("copy");
  alert("Copied the text: " + copyText.value);
}

Answer

You can also use navigator.clipboard. https://developer.mozilla.org/en-US/docs/Web/API/Navigator/clipboard

function copyToClipboard() {
  let clip = navigator.clipboard;
  if (clip === undefined) {
    console.log(
      "Upgrade your browser to use the clipboard feature.",
    );
  } else {
    navigator.clipboard.writeText(document.getElementById('my_input').value);

  }
}
<input id='my_input' />

<button onClick='copyToClipboard()' >
Click me
</button>