JavaScript

Copy Text to Clipboard Using JavaScript [execCommand]

This tutorial explains how to use JavaScript to copy text to the clipboard. On both PC and smartphone, selecting text and performing a “copy” operation is a common action. However, as a web developer, you can enhance user experience and reduce operational hassle by implementing a mechanism to copy text to the clipboard easily with JavaScript. For example, by making it easy for users to copy content entered in a form or clicked on a button to the clipboard, you can provide a more convenient interface.
This tutorial introduces a simple method to copy text to the clipboard using document.execCommand(). It also demonstrates how to implement text copying triggered by a click event using jQuery.

Why Copy Text to Clipboard?

The ability to copy text to the clipboard is useful in many situations. Here are some scenarios where this functionality is particularly convenient:

  1. Password Copying
    In login or password input forms, providing a feature that allows users to easily copy generated passwords can save effort.
  2. URL Sharing
    When users want to share a specific link or page URL, a one-click copy button enhances usability.
  3. Coupon Codes or Serial Keys
    On websites offering coupons or promotion codes, allowing users to copy the code with a single click provides a smoother experience.

In these cases, clipboard copy functionality is highly practical and enhances user convenience.

Basic CSS for Clipboard Copy

First, set up basic CSS for how to display the text area (cliptxt) that will be copied to the clipboard. The following CSS is for appearance only and does not directly affect the clipboard copy functionality but helps improve layout. Of course, you can modify it as needed.

<style>
body {
    font-family: Verdana, "Hiragino Kaku Gothic Pro", "ヒラギノ角ゴ Pro W6", Osaka, "MS Pゴシック", Arial, sans-serif;
    padding: 0;
    margin: 0;
    overflow-x: hidden;
}
ol, ul {
    list-style: none;
    margin: 0;
    padding: 0;
}
img {
    vertical-align: bottom;
    -webkit-backface-visibility: hidden;
}
h1 {
    font-size: 18px;
    line-height: 1.6em;
    text-align: center;
    font-weight: normal;
    padding: 10px 0;
}
.cliptxt {
    width: 400px;
    height: 100px;
    background-color: #cccccc;
    border: solid 2px #777777;
    text-align: center;
    line-height: 100px;
    margin: 30px auto;
}
</style>

The style applied to the .cliptxt class allows you to adjust the design of the text area intended for clipboard copying. For example, you can change the width or height values to adjust the display area size.

HTML Example

Next, here’s the HTML for the text area to be copied. Define the area containing specific text using class="cliptxt". When this area is clicked, the text is copied to the clipboard.

<h1>JavaScript Demo Page for Copying Text to Clipboard</h1>

<div align="center">Try clicking the gray area below.</div>

<div class="cliptxt">The text in this area will be copied to the clipboard.</div>

<div align="center">After clicking the gray area, open a text editor and paste (Ctrl + V).</div>

In this HTML code, the cliptxt class div tag is the target text area for clipboard copying. The contents of this text area are copied to the clipboard when clicked.

Copying Text to Clipboard Using JavaScript

Now, let’s look in detail at how to copy text to the clipboard with JavaScript. This feature is achieved with document.execCommand('copy'), but before that, text is added to a textarea tag, selected, and copied. Load the jquery.min.js file. Below is an example using jQuery.

<script src="jquery.min.js"></script>
<script type="text/javascript">
$(function () {
  $(".cliptxt").on("click", function() {
      var text = $(this).text();
      $(this).append('');
      $('.clipbtextarea').select();
      document.execCommand('copy');
      $('.clipbtextarea').remove();
      alert('[' + text + '] has been copied to the clipboard.');
  });
});
</script>

The code above achieves clipboard copying in the following steps:

  1. When the cliptxt class div is clicked, it retrieves the text inside.
  2. The retrieved text is inserted into a textarea tag and added to the screen.
  3. The textarea is selected, and document.execCommand('copy') is executed to copy to the clipboard.
  4. Once copying is complete, the added textarea is removed, and a completion alert is shown to the user.

JavaScript Demo Page for Copying Text to Clipboard

JavaScript Demo for Copying Text to Clipboard

A More Modern Approach: Clipboard API

In recent browsers, the Clipboard API is recommended as a simpler and more intuitive alternative to document.execCommand(). The Clipboard API supports asynchronous operations, making it more intuitive to use.

※ Please use this tutorial responsibly. Do not reuse the Google Analytics tags within the demo page’s head section.