Back to all resources
Clipboard API
Event Handling

Copy to Clipboard

By Jared Malan
This JavaScript code utilizes jQuery to handle a click event on any button element on a webpage. When a button is clicked, the script performs the following actions:

  1. It captures the clicked button element and its original text.
  2. It temporarily changes the button's text to "Copied!" to provide immediate visual feedback to the user.
  3. It retrieves a text value stored in a data attribute (data-content) of the button, which is intended to be the text that needs to be copied to the clipboard.
  4. It uses the Clipboard API to programmatically copy the retrieved text to the user's clipboard.
  5. It logs a message to the console indicating that the text has been copied.
  6. After a delay of 1000 milliseconds (1 second), it restores the original text of the button.
 
This script is useful for implementing a copy-to-clipboard feature on buttons where each button may have different text content to be copied.