Milind Daraniya

How to Copy Text to Clipboard using jQuery

Published June 13th, 2023 2 min read

The ability to copy text to the clipboard can enhance user experience and simplify certain actions on web applications. In this tutorial, we will explore how to implement a feature that allows users to copy text to the clipboard using jQuery.

 

Step 1: Include jQuery Library

First, ensure that you have the jQuery library included in your project. You can either download the library and host it locally or use a content delivery network (CDN) to include it in your HTML file. Here's an example of including jQuery using a CDN:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

 

Step 2: Create the HTML

Next, create an HTML element that contains the text you want to copy. For example, let's create a paragraph element with an ID for easy selection:

<p id="textToCopy">This is the text to be copied.</p>
<button id="copyButton">Copy to Clipboard</button>

Step 3: Implement the Copy Functionality

Now, using jQuery, we can implement the functionality to copy the text to the clipboard when the button is clicked. Add the following JavaScript code:

$(document).ready(function() {
  $('#copyButton').click(function() {
    var text = $('#textToCopy').text();

    var dummyElement = $('<textarea>').val(text).appendTo('body').select();
    document.execCommand('copy');
    dummyElement.remove();

    alert('Text copied to clipboard!');
  });
});

 

 

  • The click event handler is attached to the "Copy to Clipboard" button using its ID.
  • The text to be copied is retrieved from the paragraph element with the ID "textToCopy" using the .text() method.
  • A temporary <textarea> element is dynamically created, and the text is set as its value.
  • The <textarea> element is appended to the body, selected, and the document.execCommand('copy') method is used to copy the text to the clipboard.
  • Finally, the temporary <textarea> element is removed, and an alert is shown to indicate that the text has been copied.

Thanks!