copy to clipboard jquery
- Published
- Reading time
- 1 min read
- Length
- 266 words
On this page
Copy to Clipboard with jQuery#
Copying text to clipboard is a common requirement in web development. jQuery can make this process easier by providing a simple function to copy text to clipboard without any hassle.
Using jQuery Clipboard Plugin#
One of the easiest ways to copy text to clipboard using jQuery is by using a third-party plugin called jQuery Clipboard. This plugin provides a simple API that allows you to bind copy and paste events easily.
Here's an example:
// Add the jQuery Clipboard plugin to your project
<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.8/clipboard.min.js"></script>
// Initialize the plugin
new ClipboardJS('.copy-btn');
// Bind a click event to copy the text to clipboard
$('.copy-btn').click(function() {
var textToCopy = $('.text-to-copy').val();
ClipboardJS.copy(textToCopy);
});new ClipboardJS('.copy-btn')initializes the clipboard plugin with the.copy-btnclass which will be used as the trigger to copy the text to clipboard.ClipboardJS.copy(textToCopy)is the main function that copies the text to clipboard.
Using the Clipboard API#
If you don't want to use a third-party plugin, you can use the Clipboard API which is supported by most modern browsers.
Here's an example:
// Bind a click event to copy the text to clipboard
$('.copy-btn').click(function() {
var textToCopy = $('.text-to-copy').val();
navigator.clipboard.writeText(textToCopy);
});navigator.clipboard.writeText(textToCopy)is the main function that copies the text to clipboard using the Clipboard API.
Conclusion#
Copying text to clipboard with jQuery is simple and can be done in multiple ways. You can use a third-party plugin like jQuery Clipboard or use the Clipboard API directly.