skip to Main Content

I’m trying to create a small (local) page that allows me to copy frequently used texts to the clipboard by clicking on a button.

My code (see below) works so far.

Now my question:

Is there a way to adapt the Javascript code so that I don’t have to create my own/new Javascript function for every new field (there are very, very many) and never have to adjust the Javascript-Code again?

<html>
    <head>
        <title>Copy!</title>
        <script>
            function c1() {
                var c = document.getElementById("c1");
                navigator.clipboard.writeText(c.value);
            }
            function c2() {
                var c = document.getElementById("c2");
                navigator.clipboard.writeText(c.value);
            }
        </script>
    </head>
    <body>
        <span>
            I want to be copied!<br />
            <input type="text" value="First value to be copied" id="c1"> <button onclick="c1()">Copy the first value!</button>
        </span>
        <br /><br />
        <span>
            But I also want to be copied<br />
            <input type="text" value="And the second value" id="c2"> <button onclick="c2()">And now the second!</button>
        </span>
    </body>
</html>

2

Answers


  1. Here’s the solution. To copy text without editing JS. All you need to do is just add copyText class in input element.

    <!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>
      </head>
      <body>
        <!-- First text I want to copy -->
        <span>First Text</span>
        <input type="text" placeholder="Enter First Text" class="copyText" />
        <br />
    
        <!-- Second text I want to copy -->
        <span>Second Text</span>
        <input type="text" placeholder="Enter Second Text" class="copyText" />
    
        <button id="btnCopy">Copy</button>
    
        <!-- JavaScript -->
        <script>
          const button = document.querySelector("#btnCopy");
          let totalText = "";
    
          // Handle Click Event
          button.addEventListener("click", function () {
            // Get Values from input elements
            let inputElement = document.querySelectorAll(".copyText");
    
            inputElement.forEach(function (element) {
              // Add space after each character/word
              totalText += `${element.value} `;
            });
    
            // Copy text To Clipboard
            navigator.clipboard.writeText(totalText);
    
            // Clear Clipboard Text
            totalText = "";
          });
        </script>
      </body>
    </html>
    

    You can also add checks like

    if(element.nodeName === 'INPUT') {
      totalText += `${element.value} `;
    }
    
    Login or Signup to reply.
  2. Start by adding an event listener to the "copyable" zone. On click, check that the click’s target is a button OR that it has a button as its parent (to make sure we include the text within the button). If we clicked within the button, get its previous element sibling, the input and copy its value to the clipboard.

    document.querySelector("div#copyable").addEventListener(
        "click",
      function(e) {
        const theButton = e.target.closest("button");
        if (theButton) {
            const theText = theButton.previousElementSibling.value;
          navigator.clipboard.writeText(theText);
          console.log("now try pasting somewhere")
        }
        
      }
     )
    <div id="copyable">
    
    
    <span>
                I want to be copied!<br />
                <input type="text" value="First value to be copied" id="c1"> <button type="button" class="copyButton">Copy the first value!</button>
            </span>
            <br /><br />
            <span>
                But I also want to be copied<br />
                <input type="text" value="And the second value" id="c2"> <button type="button" class="copyButton">And now the second!</button>
            </span>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search