Skip to content

jQuery copy to clipboard

  • by

You can use the navigator.clipboard.writeText() method to write text to the clipboard and jQuery can be used to handle events and manipulate the DOM in a concise and readable way.

HTML:

<button id="copyButton">Copy to Clipboard</button>
<input id="copyTarget" type="text" value="Text to be copied">

jQuery

$(document).ready(function() {
  $('#copyButton').click(function() {
    var copyText = $('#copyTarget');
    copyText.select();
    document.execCommand('copy');
  });
});

It is easier to implement copy-to-clipboard functionality in your web application.

jQuery copy to clipboard example

Simple example code copying text to the clipboard using jQuery is similar to using plain JavaScript.

<!DOCTYPE html>
<html>
<head>
  <title>Copy to Clipboard</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
  <input type="text" id="myInput"><br><br>
  <button id="copyButton">Copy to clipboard</button>

  <script>
    $(document).ready(function() {
      $('#copyButton').click(function() {
        const textToCopy = $('#myInput').val();
        navigator.clipboard.writeText(textToCopy)
          .then(() => {
            console.log(`Copied "${textToCopy}" to clipboard`);
          })
          .catch((err) => {
            console.error('Could not copy text: ', err);
          });
      });
    });
  </script>
</body>
</html>

Output:

jQuery copy to clipboard

In this example, we load jQuery from a CDN using a script tag in the head of the HTML document. And defined an input field with the ID “myInput” and a button with the ID “copyButton”. Then use jQuery to attach a click event listener to the button.

When the button is clicked, we retrieve the text to copy from the input field using $('#myInput').val(). We then call the navigator.clipboard.writeText() method with the text to copy, as before.

Do comment if you have any doubts or suggestions on this jQuery topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *