Skip to content

[HTML] Copy String To Clipboard

Last Updated on 2021-10-17 by Clay

In the past I researched how to use HTML + JavaScript to copy the string to the system clipboard. The many methods are as following:

  • Create a TextArea object that contains the text we want to copy
  • Select all the content of the TextArea
  • Copy to the clipboard

But I don't want to create any object, just want a button. I thought this should be a simple function, but it was unexpectedly difficult.

By the way, if you simply set style="display: none" that cannot be copied. This is because we need to select all the text in the TextArea.

Fortunately, a suitable method was finally found, without the need for display components.


Copy method

<textarea readonly id="copyText" style="position:absolute;left:-9999px">
    It's good!
</textarea>
    <button type="button" onclick="copyEvent('copyText')">COPY</button>

<script>
    function copyEvent(id)
    {
        var str = document.getElementById(id);
        window.getSelection().selectAllChildren(str);
        document.execCommand("Copy")
    }
</script>


Output:


We only need to modify the text in "It's good!" to modify the string copied into the clipboard.

(Note: This method is not effective for Safari browser. Safari has to use a more complicated method to copy)


References


Read More

Leave a Reply