Friday, October 10, 2025
HomeLanguagesJavascriptHow to copy the text to the clipboard in JavaScript ?

How to copy the text to the clipboard in JavaScript ?

In order to copy the text to the clipboard in JavaScript we use document.execCommand() method. This can be done by following the below-mentioned approach.

Approach:

The JavaScript code will look like this:

function GeeksForGeeks() {
    /* Get the text field */
    let copyGfGText = document.getElementById("IdOfTextToCopy");
    
    /* Select the text field */
    copyGfGText.select();
    
    /* Copy the text inside the text field */
    document.execCommand("copy");
        
    /* Use below command to access the 
       value of copied text */
    console.log(copyGfGText.value);
}

Note: The document.execCommand() method is not supported in IE8 and earlier. 

Example: In this example, we will apply the above approach.

html




<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible"
          content="IE=edge">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0">
 
    <title>
        How to copy the text to the
        clipboard in JavaScript ?
    </title>
</head>
 
<body>
    <h1 style="color:green;">
        GeeksForGeeks
    </h1>
 
    <input type="text" value="GeeksForGeeks"
        id="GfGInput">
 
    <button onclick="GeeksForGeeks()">
        Copy text
    </button>
 
    <p>
        Click on the button to copy the text
        from the text field.<br> Try to paste
        the text (e.g. ctrl+v) afterwards in
        a different window, to see the effect.
    </p>
 
    <p id="gfg"></p>
 
    <script>
        function GeeksForGeeks() {
            let copyGfGText =
                document.getElementById("GfGInput");
 
            copyGfGText.select();
            document.execCommand("copy");
             
            document.getElementById("gfg")
                .innerHTML = "Copied the text: "
                + copyGfGText.value;
        }
    </script>
</body>
</html>


Output: 

How to copy the text to the clipboard in JavaScript?

How to copy the text to the clipboard in JavaScript?

RELATED ARTICLES

Most Popular

Dominic
32349 POSTS0 COMMENTS
Milvus
87 POSTS0 COMMENTS
Nango Kala
6717 POSTS0 COMMENTS
Nicole Veronica
11880 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11941 POSTS0 COMMENTS
Shaida Kate Naidoo
6838 POSTS0 COMMENTS
Ted Musemwa
7097 POSTS0 COMMENTS
Thapelo Manthata
6792 POSTS0 COMMENTS
Umr Jansen
6792 POSTS0 COMMENTS