How to Copy Text to the Clipboard with JavaScript

Introduction

Copying text to the clipboard is a useful feature that improves user experience, allowing users to quickly copy information without manually selecting and copying it. Modern JavaScript provides the Clipboard API to easily copy text to the clipboard with a button click or other triggers.

In this tutorial, you will learn how to copy text to the clipboard using JavaScript.

Problem Statement

Create a button that:

  • Copies a specified piece of text to the clipboard when clicked.

Example:

  • Input: The user clicks a "Copy" button.
  • Output: The specified text is copied to the clipboard.

Solution Steps

  1. Create an Input or Text Element: Define the text that the user can copy.
  2. Use JavaScript for Interaction: Use the Clipboard API to copy the text to the clipboard.
  3. Provide User Feedback: Display a message or indication that the text has been successfully copied.

HTML and JavaScript Structure

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Copy Text to Clipboard</title>
    <style>
        /* Simple styles for input and button */
        input {
            width: 300px;
            padding: 10px;
            font-size: 16px;
            margin-right: 10px;
        }

        button {
            padding: 10px 20px;
            background-color: #3498db;
            color: white;
            border: none;
            cursor: pointer;
            font-size: 16px;
            border-radius: 5px;
        }

        button:hover {
            background-color: #2980b9;
        }

        .copied-message {
            color: green;
            margin-top: 10px;
            display: none;
        }
    </style>
</head>
<body>

    <h2>Copy Text to Clipboard Example</h2>

    <!-- Input field for text -->
    <input type="text" id="textToCopy" value="Hello, copy this text!" readonly>
    
    <!-- Button to trigger copying the text -->
    <button onclick="copyText()">Copy</button>

    <!-- Feedback message -->
    <p id="copiedMessage" class="copied-message">Text copied to clipboard!</p>

    <script>
        // Function to copy the text
        function copyText() {
            // Select the text in the input field
            var textInput = document.getElementById("textToCopy");
            textInput.select();
            textInput.setSelectionRange(0, 99999); // For mobile devices

            // Use the Clipboard API to copy the text
            navigator.clipboard.writeText(textInput.value).then(function() {
                // Show the feedback message
                var copiedMessage = document.getElementById("copiedMessage");
                copiedMessage.style.display = 'block';

                // Hide the message after 2 seconds
                setTimeout(function() {
                    copiedMessage.style.display = 'none';
                }, 2000);
            }).catch(function(error) {
                console.error("Failed to copy text: ", error);
            });
        }
    </script>

</body>
</html>

Output

You can play with the above HTML in Online HTML Editor and Compiler. Here is the output of the above HTML page.:

Explanation

Step 1: Create an Input Field for the Text

In this example, we have an input field (<input>) containing the text that the user can copy. The input field is marked as readonly to prevent users from editing the text.

<input type="text" id="textToCopy" value="Hello, copy this text!" readonly>
  • readonly: Prevents the input field from being edited by the user.

  • value="Hello, copy this text!": Sets the default text that will be copied.

Step 2: Create a Button to Trigger the Copy Action

The button triggers the copyText() JavaScript function when clicked. This function copies the text from the input field to the clipboard.

<button onclick="copyText()">Copy</button>

Step 3: JavaScript to Copy Text to Clipboard

The copyText() function handles copying the text from the input field using the Clipboard API. Here's how the function works:

function copyText() {
    // Select the text in the input field
    var textInput = document.getElementById("textToCopy");
    textInput.select(); // Selects the text in the input
    textInput.setSelectionRange(0, 99999); // Ensures selection works on mobile

    // Use the Clipboard API to copy the selected text
    navigator.clipboard.writeText(textInput.value).then(function() {
        // Success: Show feedback message
        var copiedMessage = document.getElementById("copiedMessage");
        copiedMessage.style.display = 'block';

        // Hide the message after 2 seconds
        setTimeout(function() {
            copiedMessage.style.display = 'none';
        }, 2000);
    }).catch(function(error) {
        console.error("Failed to copy text: ", error); // Handle errors
    });
}
  • textInput.select(): Selects the text inside the input field.

  • navigator.clipboard.writeText(): Copies the selected text to the clipboard.

  • setTimeout(): Hides the "Text copied to clipboard!" message after 2 seconds.

Step 4: Provide User Feedback

When the text is successfully copied to the clipboard, a message (<p>) appears to notify the user. This message is hidden by default and shown only when the copy action is successful.

<p id="copiedMessage" class="copied-message">Text copied to clipboard!</p>

The copiedMessage is styled to be green and hidden initially using the display: none CSS rule:

.copied-message {
    color: green;
    margin-top: 10px;
    display: none;
}
  • display: none: Hides the message initially.

Customization

Copy Text from a Paragraph or Div

You can modify the example to copy text from other elements, such as a <p> or <div> tag, by using innerText instead of value. For example:

<p id="textToCopy">This is some text to copy!</p>
<button onclick="copyText()">Copy</button>

<script>
function copyText() {
    var text = document.getElementById("textToCopy").innerText;
    navigator.clipboard.writeText(text).then(function() {
        alert("Text copied: " + text);
    });
}
</script>

Copy Dynamic Text

To copy dynamic text generated by JavaScript, you can update the content inside the input or another element before copying it:

document.getElementById("textToCopy").value = "New dynamic text";
copyText();

Copy with Feedback Alerts

If you'd like to use an alert to notify the user, you can display an alert directly in the then() method:

navigator.clipboard.writeText(textInput.value).then(function() {
    alert("Text copied to clipboard!");
});

Conclusion

Copying text to the clipboard using JavaScript is a simple and useful functionality that can enhance user experience. The Clipboard API makes it easy to implement this feature. You can further customize the script to fit your needs, such as copying from different elements or providing different feedback to the user.

Comments