Textarea on Click Copy Text Using JavaScript

Textarea on Click Copy Text Using JavaScript

Have you ever needed to copy text from a textarea element on a web page? Maybe you want to allow users to copy a code snippet or other piece of text with a single click. In this post, we'll learn how to copy text from a textarea on click using JavaScript, and we'll also see how to display a "Copied" message in the center of the screen to confirm that the text has been copied.

Here's a simple example of how you can do this:

Textarea on Click Copy Text Using JavaScript Example

<textarea id="textarea">This text will be copied on click.</textarea>
<div id="message">Copied</div>

<style>
  #message {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: #ccc;
    border-radius: 5px;
    padding: 5px 10px;
    display: none;
  }
</style>

<script>
  const textarea = document.getElementById('textarea');
  const message = document.getElementById('message');

  textarea.addEventListener('click', () => {
    navigator.clipboard.writeText(textarea.value).then(() => {
      message.style.display = 'block';
      setTimeout(() => {
        message.style.display = 'none';
      }, 2000); // hide the message after 2 seconds
    });
  });
</script>

This code adds a click event listener to the textarea element. When the textarea is clicked, the text inside it is copied to the clipboard using the navigator.clipboard.writeText() function. Then, it displays the "Copied" message and hides it after 2 seconds.

This code positions the message element using the position, top, and left properties, and uses the transform: translate(-50%, -50%) property to center it on the screen. The background-color, border-radius, and padding properties are used to style the message element. The display property is used to show and hide the message element as needed. Below is the live example:

Note: Below code may not work on your browser due to the Clipboard permission issue. Please click on Edit on Codepen to view example directly on Codepen.

See the Pen copy textarea text on click by Vinish Kapoor (@foxinfotech) on CodePen.

Related: