Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Learn how to copy text and paste to clipboard using javascript

    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1
    • 0
    • 754
    Comment on it

    Hii,

    To learn how we can copy text and paste to clipboard using very simple few lines of javascript code,Go through the given example below
    In this example execCommand() plays an important role in the following way:
    Step 1: I have a html tag i.e <p></p> inside which some text is written. That P tag is having an unique ID "text_element". 


    <p id="text_element">Copy this !</p>

     

    Step 2: Now a javascript onclick event is added in a html tag i.e a button . 


    <button onclick="copyToClipboard('text_element')">
        Copy to clipboard
    </button>


    Step 3 : Create a function inside script tag having name same as declared inside button's onclick event.


    function copyToClipboard(elementId)


    When the user will click on the button  javascript  code will run on client side to copy the text written within the P tag , the moment user clicks on the button execCommand will run to copied the text.

    Example:

    <body>
    <p id="text_element">Copy me and paste me wherever you want!</p>
    
    <button onclick="copyToClipboard('text_element')">
      Copy to clipboard
    </button>
    <br/><br/><input type="text" placeholder="Paste here for checking" />
    <script type="text/javascript">
     function copyToClipboard(elementId) {
    
      var PasteContent = document.createElement("input");
    
    
     PasteContent.setAttribute("value", document.getElementById(elementId).innerHTML);
    
    
     document.body.appendChild(PasteContent);
    
    
     PasteContent.select();
     document.execCommand("copy");
     document.body.removeChild(PasteContent);
    
    }
    
    </script>
    </body>


     

    Learn how to copy text and paste to clipboard using javascript

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: