Skip to content

[HTML] Make a Button to Copy Text

I have always wanted to make a button to copy the text of a html block, that can help a project I am developing very well. Therefore, I studied it today and recorded it.

The method of implementation is also quite simple. You only need to set the ID of the block to be copied.


Demo

<p id="copy">This is the copy string!</p>
<button type="button" onclick="copyEvent('copy')">Copy</button>

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



The top block, the block with id="copy", is the text I expect to copy “This is the copy string!”. Below is a simple button, which is triggered by the JavaScript script below.

In JS, I defined a copyEvent() function, which is mainly to copy the string corresponding to the block with a specific ID.

The displayed screen is as follows:

After clicking, find a notepad to paste:

3 thoughts on “[HTML] Make a Button to Copy Text”

    1. Yes you can, you will just need to establish a new copyEvent function for the new ID that was created for the second paragraph and button.

Leave a Reply