• Breaking News

    Monday, 28 December 2015

    Copy Text To Clipboard By jQuery

    Copy Text To Clipboard by jQuery or JavaScript:
    You need to select the text and then execute the command copy to copy to the clipboard whatever text is currently selected on the page.
    For example, this function will copy the content of the passed element into the clipboard.

    This is how it works:
    1.    Creates a text field that contain text.
    2.    Selects the content of the text field.
    3.    Copies the content of the element to that text field by click on.
    4.    Executes the command copy like: document.execCommand("copy").
    5.    Removes the temporary text field.

    JQuery Code:
    This is the main function that execute the 'copy' command (that is already define in the browser) on bases of the browser security.

    //CopyToClip.js
    (function(){
       $("#btnCopy").click(function(){
           btnCopyFunc();
       });
    }).apply(this,[jQuery]);

    function btnCopyFunc(){
       $("#txtCopy").text();
       try {
           var successful = document.execCommand('copy');
           var msg = successful ? 'successful' : 'unsuccessful';
           alert('Selected text copy to clipboard is ' + msg);
       }catch (err) {
           alert('Oops, unable to copy');
       }

    }


    HTML code:
    <!DOCTYPE html>
    <html>
       <head>
          <script type="text/javascript" src="jquery.js"></script>
          <script type="text/javascript" src="CopyToClip.js"></script>
       </head>

       <body>
          <a id="txtCopy" >Here is the text that you to Copy it to clipboard.</a>
          <input type="button" value="Copy" id="btnCopy" onclick=" return btnCopyFunc()"/>
       </body>
    </html>

    The main issue is that not all browsers support this feature at the moment, but you can use it on the main ones from:
    ·         Chrome 43
    ·         Internet Explorer 10
    ·         Firefox 41

    -------------------Thanks for learning-------------------


    No comments:

    Post a Comment