Skip to content
Related Articles

Related Articles

How to copy the text to the clipboard in JavaScript?
  • Last Updated : 20 Mar, 2019

In order to copy the text to the clipboard in javascript we use document.execCommand() method . This can be done in two steps
Step1 : Write HTML code:




<!-- The text field -->
<input type="text" value="GeeksForGeeks" id="GfGInput">
  
<!-- The button used to copy the text -->
<button onclick="GeeksForGeeks()">Copy text</button

Step2 : Write JavaScript code:




function GeeksForGeeks() {
  /* Get the text field */
  var copyGfGText = document.getElementById("GfGInput");
  
  /* Select the text field */
  copyGfGText.select();
  
  /* Copy the text inside the text field */
  document.execCommand("copy");
  
  /* Alert the copied text */
  alert("Copied the text: " + copyGfGText.value);

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

Example 1:




<!DOCTYPE html>
<html>
    <body style = "text-align:center;">
        <h1 style = "color:green;" >  
            GeeksForGeeks  
        </h1>
        <input type="text" value="GeeksForGeeks" id="GfGInput">
        <button onclick="GeeksForGeeks()">Copy text</button
        <script>
            function GeeksForGeeks() {
              var copyGfGText = document.getElementById("GfGInput");
              copyGfGText.select();
              document.execCommand("copy");
              alert("Copied the text: " + copyGfGText.value);
            
        </script>
        <p>
            Click on the button to copy the text from the
            text field. Try to paste the text (e.g. ctrl+v)
            afterwards in a different window, to see the
            effect.
        </p>
    </body>
</html>

Output :

After clicking on element:

Selected text is copied:

Example 2:




<!DOCTYPE html>
<html>
    <head>
        <style
            h1 { 
            border: 1px solid black; 
            height: 90px; 
            padding-top: 40px; 
            background: green; 
            color: white; 
            
        </style>
    </head>
    <body style = "text-align:center;">
        <h1 style = "color:white;" >  
            GeeksForGeeks  
        </h1>
        <input type="text" value="GeeksForGeeks" id="GfGInput">
        <button onclick="GeeksForGeeks()">Copy text</button
        <script>
            function GeeksForGeeks() {
              var copyGfGText = document.getElementById("GfGInput");
              copyGfGText.select();
              document.execCommand("copy");
              alert("Copied the text: " + copyGfGText.value);
            
        </script>
        <p>Click on the button to copy the text from the field.
            Try to paste the text (e.g. "ctrl+v")to see the effect.
        </p>
    </body>
</html>

Output :

After clicking on element:

Selected text is copied:




My Personal Notes arrow_drop_up
Recommended Articles
Page :