JavaScript: Copy to Clipboard

JavaScript: Copy to Clipboard

Β·

7 min read

Copying text to a clipboard can be a helpful feature on a website. User's can save a step or two if that feature is available, which helps them to not lose their patience while on your site. If you've ever worked with an end user, or done any User Acceptance Testing, then I'm sure you're familiar with each request that comes in about something being easier or less "painful" to use.

I'll be using pure JavaScript in this example. No JQuery, or TypeScript needed.

Let's get right into it!

Our Example Situation

We'll use the situation of a 6-digit security code. We'll provide our user with a code and the option to copy it to their clipboard.

The first version of the ability to work with the clipboard in JavaScript used the execCommand() function. This feature is now deprecated and it is recommended that you use the newer Clipboard API.

If the syntax of the Clipboard API is somewhat confusing, don't worry. It uses JavaScript Promises which are an amazing way to make asynchronous code more manageable. I won't get into that here, but I hope to in the near future.

Have a look at the following code snippet:

<!DOCTYPE html>
<html>
<head>
    <title>JavaScript | Copy to Clipboard</title>
</head>
<body>
    <section>
        <input type="text" id="securityCode" value="154678" disabled/>
        <button type="button" id="copyToClipboard">Copy to Clipboard</button>
    </section>

    <script>
        // Setup our page element selectors
        var securityCodeElement = document.getElementById("securityCode");
        var copyToClipboardBtn = document.getElementById("copyToClipboard");

        // Listen to the "click" event on our copy to clipboard button
        copyToClipboardBtn.addEventListener("click", function()
        {
            // The value of the security code
            var securityCodeValue = securityCodeElement.value;

            // The magic! Here is where we actually copy the value to the clipboard
            // Notice that we "pass" our security code value to the writeText() function
            // which is inside of the clipboard class
            navigator.clipboard.writeText(securityCodeValue).then(() =>
            {
                // Success! Now let the user know what that value was
                alert("Text copied to clipboard! Value: " + securityCodeValue);
            }).catch((error) =>
            {
                // Umm, what the heck? It doesn't work. To the debugger!
                alert("Oops! Something went wrong: ", error);
            });
        });
    </script>
</body>
</html>

The first section, of course, simply sets up our HTML to contain the code to copy and a convenient copy to clipboard button:

<section>
        <input type="text" id="securityCode" value="154678" disabled/>
        <button type="button" id="copyToClipboard">Copy to Clipboard</button>
    </section>

Then, inside of our inline script section we attach those elements to a variable:

// Setup our page element selectors
        var securityCodeElement = document.getElementById("securityCode");
        var copyToClipboardBtn = document.getElementById("copyToClipboard");

Once we have those attached we get to the meat and potatoes of the code. Here, we take advantage of the newer Clipboard API to set a new clipboard value:

// Listen to the "click" event on our copy to clipboard button
        copyToClipboardBtn.addEventListener("click", function()
        {
            // The value of the security code
            var securityCodeValue = securityCodeElement.value;

            // The magic! Here is where we actually copy the value to the clipboard
            // Notice that we "pass" our security code value to the writeText() function
            // which is inside of the clipboard class
            navigator.clipboard.writeText(securityCodeValue).then(() =>
            {
                // Success! Now let the user know what that value was
                alert("Text copied to clipboard! Value: " + securityCodeValue);
            }).catch((error) =>
            {
                // Umm, what the heck? It doesn't work. To the debugger!
                alert("Oops! Something went wrong: ", error);
            });
        });

The navigator code is something that "represents the state and the identity of the user agent ." What does that mean? Essentially it is a means to get information from whatever browser the user is currently on. It can gather details about the userAgent, their language, the platform and many other details.

The information we are taking advantage of in this code is the navigator.clipboard(), which is a writeable function inside of the navigator class and allows us to set a value to our system clipboard.

Once you run this code snippet in a browser you can then check that it worked by clicking the Windows Key + V. This will open up your clipboard history. In there you should see the copied value as the the top value in the list. Congratulations you just copied out a value from a webpage to your clipboard!

The clipboard feature likely doesn't have a ton of use cases, other than making things more convenient for end users, but it is something that is fun to learn how to use. You can combine this with the other feature I wrote about, How to Capture Highlighted Text, and make the feature even more robust.

Hopefully you'll have come away with some new knowledge about JavaScript. As anyone will tell you JavaScript never ceases to amaze when it comes to what it can do for you. The features seem endless, and this one is no exception. It's an old-school kind of thing, but still very useful even today.


Photo by Ralph (Ravi) Kayden on Unsplash

Did you find this article valuable?

Support Charles J by becoming a sponsor. Any amount is appreciated!

Β