Copying text to the client's clipboard involves several steps:
To accomplish this using jQuery, follow these steps:
<code class="html"><script src="https://code.jquery.com/jquery-3.6.0.min.js"></script></code>
<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!