DEV Community

Cover image for How to Make a Copy to Clipboard with Javascript
Hilmi Hidayat
Hilmi Hidayat

Posted on • Edited on

How to Make a Copy to Clipboard with Javascript

Have you ever seen on a website page there is a copy URL to clipboard feature? This feature really helps users or visitors to copy URLs from website posts, so that users don't need to copy or copy URLs manually. Do you intend to add a copy URL to clipboard feature on your website? if so, you are absolutely right to read this article because in this article we will both learn how to create the URL to clipboard copy feature using javascript. The method is very easy, we only need to prepare a text editor, browser and internet network (optional).

The following is a sample code for creating the copy to clipboard feature.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Copy to Clipboard</title>
    </head>
    <body>
        <!-- The text field -->
        <input type="text" value="https://bisabos.com/blog/cara-membuat-animasi-mengetik-teks-dengan-css-dan-javascript" id="copyText" readonly>
        <!-- The button used to copy the text -->
        <button id="copyBtn">Copy text</button>
        <!--using sweetalert via CDN -->
        <script src="https://cdn.jsdelivr.net/npm/sweetalert2@10"></script>
        <script>
            const copyBtn = document.getElementById('copyBtn')
            const copyText = document.getElementById('copyText')

            copyBtn.onclick = () => {
                copyText.select();    // Selects the text inside the input
                document.execCommand('copy');    // Simply copies the selected text to clipboard 
                 Swal.fire({         //displays a pop up with sweetalert
                    icon: 'success',
                    title: 'Text copied to clipboard',
                    showConfirmButton: false,
                    timer: 1000
                });
            }
        </script>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Read more at codelapan.com

Top comments (2)

Collapse
 
apoorvacg profile image
Apoorva CG

Hi Hilmi, to update this blog for anyone new here that document.execCommand has been officially deprecated. You can check it out here

You can use the Clipboard API for the same which is designed to replace the document.execCommand.

Collapse
 
prakh_r profile image
Prakhar Yadav

will this prompt the user to give the webpage some permission for allowing to copy?