```html How to Create a Copy Button with JavaScript | Complete Clipboard API Guide for Beginners

How to Create a Copy Button with JavaScript

3. Copying Text with JavaScript

JavaScript is a programming language that adds interactivity and dynamic behavior to web pages.

On this page, JavaScript is used to retrieve the text from a textarea when the user clicks the copy button, and then copy that text to the system clipboard.

The feature used in this example is the Clipboard API, specifically navigator.clipboard.writeText(). It is the recommended modern method for copying text and is supported by most current web browsers.

Example Code

function copyText(){

const text = document.getElementById("text").value;

navigator.clipboard.writeText(text);

}

Code Explanation

① function copyText()

This creates a function named copyText(). The function runs whenever the user clicks the copy button.

② document.getElementById("text").value

This retrieves the current text entered in the textarea whose ID is text.

③ navigator.clipboard.writeText(text)

This copies the retrieved text to the system clipboard.

How It Works

  1. Click the 📋 Copy button.
  2. The copyText() function is executed.
  3. The text inside the textarea is retrieved.
  4. The Clipboard API copies the text to the clipboard.
  5. Paste the copied text anywhere using Ctrl + V (Windows) or ⌘ + V (Mac).

Key Points

```