How to Create a Button to Copy Text in HTML

How to Create a Button to Copy Text in HTML

How to Create a Button to Copy Text in HTML

Copying text is a common requirement in web applications. In this blog post, we will explore how to create a button in HTML that allows users to copy text with a simple click. This functionality can be handy for sharing snippets, URLs, or any other text content with ease.

HTML Markup

To create the copy button, we need to use HTML and JavaScript together. Let's take a look at the HTML markup required:


      <p id="text-to-copy">This is the text to be copied.</p>
      <button id="copy-btn">Copy</button>
    

In this example, we have a paragraph element with the id "text-to-copy," which contains the text that we want to copy. Below the paragraph, there is a button element with the id "copy-btn," which serves as our copy button.

JavaScript Function

To enable the copy functionality, we need to add JavaScript to our HTML. Here's the JavaScript function that will be executed when the copy button is clicked:


      <script>
        function copyText() {
          var textToCopy = document.getElementById("text-to-copy").textContent;
          navigator.clipboard.writeText(textToCopy)
            .then(function() {
              alert("Text copied successfully!");
            })
            .catch(function(error) {
              console.error("Error copying text: ", error);
            });
        }
      </script>
    

The copyText() function retrieves the text to be copied by accessing the content of the element with the id "text-to-copy." It then uses the Clipboard API's writeText() method to copy the text to the clipboard. If the copying process is successful, an alert is displayed with the message "Text copied successfully!" If any error occurs during the copy operation, an error message is logged to the console.

Event Binding

Finally, we need to bind the JavaScript function to the button's click event. We can achieve this by adding an onclick attribute to the button element:


      <button id="copy-btn" onclick="copyText()">Copy</button>
    

When the button is clicked, the copyText() function will be invoked, triggering the text copy operation.

Conclusion

Creating a button to copy text in HTML can be accomplished by combining HTML, JavaScript, and the Clipboard API. By following the steps outlined in this blog post, you can empower users to easily copy text from your web application, enhancing their experience and facilitating content sharing.

Comments