Home  >  Article  >  Web Front-end  >  How to Copy Text to Client\'s Clipboard with jQuery?

How to Copy Text to Client\'s Clipboard with jQuery?

Susan Sarandon
Susan SarandonOriginal
2024-10-19 12:02:02652browse

How to Copy Text to Client's Clipboard with jQuery?

Copy Text to Client's Clipboard with jQuery

Copying text to the client's clipboard involves several steps:

  1. Trigger copying upon a click within a textarea.
  2. Transfer the selected text to the clipboard.
  3. Provide user feedback on the action.

To accomplish this using jQuery, follow these steps:

  1. Include jQuery in your HTML document if it's not already present.
<code class="html"><script src="https://code.jquery.com/jquery-3.6.0.min.js"></script></code>
  1. Create a textarea element and attach an event listener to its click event:
<code class="html"><textarea id="my-textarea"></textarea>

<script>
$( "#my-textarea" ).on( "click", function() {
  // Get the selected text
  var selectedText = $(this).val();

  // Clipboard API is not supported in all browsers
  if (!navigator.clipboard) {
    console.error("Clipboard API not supported");
    return;
  }

  // Set the selected text to the clipboard
  navigator.clipboard.writeText(selectedText).then(() => {
    // Success
    alert("Text copied to clipboard!");
  }, () => {
    // Error
    alert("Failed to copy text to clipboard");
  });
});
</script></code>

This approach uses the Clipboard API, which is supported by most modern browsers. If your target audience includes older browsers, consider using a fallback method, such as using ZeroClipboard or Flash, as described in the provided answer.

The above is the detailed content of How to Copy Text to Client\'s Clipboard with jQuery?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn