[jquery] Click button copy to clipboard using jQuery

How do I copy the text inside a div to the clipboard? I have a div and need to add a link which will add the text to the clipboard. Is there a solution for this?

<p class="content">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s</p>

<a class="copy-text">copy Text</a>

After I click copy text, then I press Ctrl + V, it must be pasted.

This question is related to jquery html css

The answer is


Update 2020: This solution uses execCommand. While that feature was fine at the moment of writing this answer, it is now considered obsolete. It will still work on many browsers, but its use is discouraged as support may be dropped.

There is another non-Flash way (apart from the Clipboard API mentioned in jfriend00's answer). 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 (updated with suggestion in the comments from PointZeroTwo):

function copyToClipboard(element) {
    var $temp = $("<input>");
    $("body").append($temp);
    $temp.val($(element).text()).select();
    document.execCommand("copy");
    $temp.remove();
}

This is how it works:

  1. Creates a temporarily hidden text field.
  2. Copies the content of the element to that text field.
  3. Selects the content of the text field.
  4. Executes the command copy like: document.execCommand("copy").
  5. Removes the temporary text field.

NOTE that the inner text of the element can contain whitespace. So if you want to use if for example for passwords you may trim the text by using $(element).text().trim() in the code above.

You can see a quick demo here:

_x000D_
_x000D_
function copyToClipboard(element) {
  var $temp = $("<input>");
  $("body").append($temp);
  $temp.val($(element).text()).select();
  document.execCommand("copy");
  $temp.remove();
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p id="p1">P1: I am paragraph 1</p>
<p id="p2">P2: I am a second paragraph</p>
<button onclick="copyToClipboard('#p1')">Copy P1</button>
<button onclick="copyToClipboard('#p2')">Copy P2</button>
<br/><br/><input type="text" placeholder="Paste here for test" />
_x000D_
_x000D_
_x000D_

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
  • Safari 10

Update 1: This can be achieved also with a pure JavaScript solution (no jQuery):

_x000D_
_x000D_
function copyToClipboard(elementId) {

  // Create a "hidden" input
  var aux = document.createElement("input");

  // Assign it the value of the specified element
  aux.setAttribute("value", document.getElementById(elementId).innerHTML);

  // Append it to the body
  document.body.appendChild(aux);

  // Highlight its content
  aux.select();

  // Copy the highlighted text
  document.execCommand("copy");

  // Remove it from the body
  document.body.removeChild(aux);

}
_x000D_
<p id="p1">P1: I am paragraph 1</p>
<p id="p2">P2: I am a second paragraph</p>
<button onclick="copyToClipboard('p1')">Copy P1</button>
<button onclick="copyToClipboard('p2')">Copy P2</button>
<br/><br/><input type="text" placeholder="Paste here for test" />
_x000D_
_x000D_
_x000D_

Notice that we pass the id without the # now.

As madzohan reported in the comments below, there is some strange issue with the 64-bit version of Google Chrome in some cases (running the file locally). This issue seems to be fixed with the non-jQuery solution above.

Madzohan tried in Safari and the solution worked but using document.execCommand('SelectAll') instead of using .select() (as specified in the chat and in the comments below).

As PointZeroTwo points out in the comments, the code could be improved so it would return a success/failure result. You can see a demo on this jsFiddle.


UPDATE: COPY KEEPING THE TEXT FORMAT

As a user pointed out in the Spanish version of StackOverflow, the solutions listed above work perfectly if you want to copy the content of an element literally, but they don't work that great if you want to paste the copied text with format (as it is copied into an input type="text", the format is "lost").

A solution for that would be to copy into a content editable div and then copy it using the execCommand in a similar way. Here there is an example - click on the copy button and then paste into the content editable box below:

_x000D_
_x000D_
function copy(element_id){
  var aux = document.createElement("div");
  aux.setAttribute("contentEditable", true);
  aux.innerHTML = document.getElementById(element_id).innerHTML;
  aux.setAttribute("onfocus", "document.execCommand('selectAll',false,null)"); 
  document.body.appendChild(aux);
  aux.focus();
  document.execCommand("copy");
  document.body.removeChild(aux);
}
_x000D_
#target {
  width:400px;
  height:100px;
  border:1px solid #ccc;
}
_x000D_
<p id="demo"><b>Bold text</b> and <u>underlined text</u>.</p>
<button onclick="copy('demo')">Copy Keeping Format</button> 

<div id="target" contentEditable="true"></div>
_x000D_
_x000D_
_x000D_

And in jQuery, it would be like this:

_x000D_
_x000D_
function copy(selector){
  var $temp = $("<div>");
  $("body").append($temp);
  $temp.attr("contenteditable", true)
       .html($(selector).html()).select()
       .on("focus", function() { document.execCommand('selectAll',false,null); })
       .focus();
  document.execCommand("copy");
  $temp.remove();
}
_x000D_
#target {
  width:400px;
  height:100px;
  border:1px solid #ccc;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<p id="demo"><b>Bold text</b> and <u>underlined text</u>.</p>
<button onclick="copy('#demo')">Copy Keeping Format</button> 

<div id="target" contentEditable="true"></div>
_x000D_
_x000D_
_x000D_


you can just using this lib for easy realize the copy goal!

https://clipboardjs.com/

Copying text to the clipboard shouldn't be hard. It shouldn't require dozens of steps to configure or hundreds of KBs to load. But most of all, it shouldn't depend on Flash or any bloated framework.

That's why clipboard.js exists.

or

https://github.com/zeroclipboard/zeroclipboard

http://zeroclipboard.org/

The ZeroClipboard library provides an easy way to copy text to the clipboard using an invisible Adobe Flash movie and a JavaScript interface.


Simplicity is the ultimate sophistication.
If you don't want the text-to-be-coppied to be visible:

jQuery:

$('button.copyButton').click(function(){
    $(this).siblings('input.linkToCopy').select();      
    document.execCommand("copy");
});

HTML:

<button class="copyButton">click here to copy</button>
<input class="linkToCopy" value="TEXT TO COPY"
style="position: absolute; z-index: -999; opacity: 0;" />

It is a simplest method to copy the content

 <div id="content"> Lorepm ispum </div>
 <button class="copy" title="content">Copy Sorce</button>

function SelectContent(element) {
                        var doc = document
                            , text = doc.getElementById(element)
                            , range, selection
                        ;    
                        if (doc.body.createTextRange) {
                            range = document.body.createTextRange();
                            range.moveToElementText(text);
                            range.select();
                        } else if (window.getSelection) {
                            selection = window.getSelection();        
                            range = document.createRange();
                            range.selectNodeContents(text);
                            selection.removeAllRanges();
                            selection.addRange(range);

                        }
                         document.execCommand('Copy');
                    }
                    $(".copy").click(function(){

                         SelectContent( $(this).attr('title'));
                    });

Clipboard-polyfill library is a polyfill for the modern Promise-based asynchronous clipboard API.

install in CLI:

npm install clipboard-polyfill 

import as clipboard in JS file

window.clipboard = require('clipboard-polyfill');

example

I'm using it in a bundle with require("babel-polyfill"); and tested it on chrome 67. All good for production.


Both will works like a charm :),

JAVASCRIPT:

function CopyToClipboard(containerid) {
if (document.selection) { 
    var range = document.body.createTextRange();
    range.moveToElementText(document.getElementById(containerid));
    range.select().createTextRange();
    document.execCommand("copy"); 

} else if (window.getSelection) {
    var range = document.createRange();
     range.selectNode(document.getElementById(containerid));
     window.getSelection().addRange(range);
     document.execCommand("copy");
     alert("text copied") 
}}

Also in html,

<button id="button1" onclick="CopyToClipboard('div1')">Click to copy</button>

<div id="div1" >Text To Copy </div>

<textarea placeholder="Press ctrl+v to Paste the copied text" rows="5" cols="20"></textarea>

JQUERY: https://paulund.co.uk/jquery-copy-clipboard


Even better approach without flash or any other requirements is clipboard.js. All you need to do is add data-clipboard-target="#toCopyElement" on any button, initialize it new Clipboard('.btn'); and it will copy the content of DOM with id toCopyElement to clipboard. This is a snippet that copy the text provided in your question via a link.

One limitation though is that it does not work on safari, but it works on all other browser including mobile browsers as it does not use flash

_x000D_
_x000D_
$(function(){_x000D_
  new Clipboard('.copy-text');_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdn.jsdelivr.net/clipboard.js/1.5.12/clipboard.min.js"></script>_x000D_
_x000D_
<p id="content">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s</p>_x000D_
_x000D_
<a class="copy-text" data-clipboard-target="#content" href="#">copy Text</a>
_x000D_
_x000D_
_x000D_


You can use this code for copy input value in page in Clipboard by click a button

This is Html

<input type="text" value="xxx" id="link" class="span12" />
<button type="button" class="btn btn-info btn-sm" onclick="copyToClipboard('#link')">
    Copy Input Value
</button>

Then for this html , we must use this JQuery Code

function copyToClipboard(element) {
    $(element).select();
    document.execCommand("copy");
}

This is the simplest solution for this question


Most of the proposed answers create an extra temporary hidden input element(s). Because most browsers nowadays support div content edit, I propose a solution that does not create hidden element(s), preserve text formatting and use pure JavaScript or jQuery library.

Here is a minimalist skeleton implementation using the fewest lines of codes I could think of:

_x000D_
_x000D_
//Pure javascript implementation:_x000D_
document.getElementById("copyUsingPureJS").addEventListener("click", function() {_x000D_
  copyUsingPureJS(document.getElementById("copyTarget"));_x000D_
  alert("Text Copied to Clipboard Using Pure Javascript");_x000D_
});_x000D_
_x000D_
function copyUsingPureJS(element_id) {_x000D_
  element_id.setAttribute("contentEditable", true);_x000D_
  element_id.setAttribute("onfocus", "document.execCommand('selectAll',false,null)");_x000D_
  element_id.focus();_x000D_
  document.execCommand("copy");_x000D_
  element_id.removeAttribute("contentEditable");_x000D_
  _x000D_
}_x000D_
_x000D_
//Jquery:_x000D_
$(document).ready(function() {_x000D_
  $("#copyUsingJquery").click(function() {_x000D_
    copyUsingJquery("#copyTarget");_x000D_
  });_x000D_
 _x000D_
_x000D_
  function copyUsingJquery(element_id) {_x000D_
    $(element_id).attr("contenteditable", true)_x000D_
      .select()_x000D_
      .on("focus", function() {_x000D_
        document.execCommand('selectAll', false, null)_x000D_
      })_x000D_
      .focus()_x000D_
    document.execCommand("Copy");_x000D_
    $(element_id).removeAttr("contenteditable");_x000D_
     alert("Text Copied to Clipboard Using jQuery");_x000D_
  }_x000D_
});
_x000D_
#copyTarget {_x000D_
  width: 400px;_x000D_
  height: 400px;_x000D_
  border: 1px groove gray;_x000D_
  color: navy;_x000D_
  text-align: center;_x000D_
  box-shadow: 0 4px 8px 0 gray;_x000D_
}_x000D_
_x000D_
#copyTarget h1 {_x000D_
  color: blue;_x000D_
}_x000D_
_x000D_
#copyTarget h2 {_x000D_
  color: red;_x000D_
}_x000D_
_x000D_
#copyTarget h3 {_x000D_
  color: green;_x000D_
}_x000D_
_x000D_
#copyTarget h4 {_x000D_
  color: cyan;_x000D_
}_x000D_
_x000D_
#copyTarget h5 {_x000D_
  color: brown;_x000D_
}_x000D_
_x000D_
#copyTarget h6 {_x000D_
  color: teal;_x000D_
}_x000D_
_x000D_
#pasteTarget {_x000D_
  width: 400px;_x000D_
  height: 400px;_x000D_
  border: 1px inset skyblue;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="copyTarget">_x000D_
  <h1>Heading 1</h1>_x000D_
  <h2>Heading 2</h2>_x000D_
  <h3>Heading 3</h3>_x000D_
  <h4>Heading 4</h4>_x000D_
  <h5>Heading 5</h5>_x000D_
  <h6>Heading 6</h6>_x000D_
  <strong>Preserve <em>formatting</em></strong>_x000D_
  <br/>_x000D_
</div>_x000D_
_x000D_
<button id="copyUsingPureJS">Copy Using Pure JavaScript</button>_x000D_
<button id="copyUsingJquery">Copy Using jQuery</button>_x000D_
<br><br> Paste Here to See Result_x000D_
<div id="pasteTarget" contenteditable="true"></div>
_x000D_
_x000D_
_x000D_


Pure JS, without inline onclick, for paired classes "content - copy button". Would be more comfortable, if you have many elements)

_x000D_
_x000D_
(function(){_x000D_
_x000D_
/* Creating textarea only once, but not each time */_x000D_
let area = document.createElement('textarea');_x000D_
document.body.appendChild( area );_x000D_
area.style.display = "none";_x000D_
_x000D_
let content = document.querySelectorAll('.js-content');_x000D_
let copy    = document.querySelectorAll('.js-copy');_x000D_
_x000D_
for( let i = 0; i < copy.length; i++ ){_x000D_
  copy[i].addEventListener('click', function(){_x000D_
    area.style.display = "block";_x000D_
    /* because the classes are paired, we can use the [i] index from the clicked button,_x000D_
    to get the required text block */_x000D_
    area.value = content[i].innerText;_x000D_
    area.select();_x000D_
    document.execCommand('copy');   _x000D_
    area.style.display = "none";_x000D_
_x000D_
    /* decorative part */_x000D_
    this.innerHTML = 'Cop<span style="color: red;">ied</span>';_x000D_
    /* arrow function doesn't modify 'this', here it's still the clicked button */_x000D_
    setTimeout( () => this.innerHTML = "Copy", 2000 );_x000D_
  });_x000D_
}_x000D_
_x000D_
})();
_x000D_
hr { margin: 15px 0; border: none; }
_x000D_
<span class="js-content">1111</span>_x000D_
<button class="js-copy">Copy</button>_x000D_
<hr>_x000D_
<span class="js-content">2222</span>_x000D_
<button class="js-copy">Copy</button>_x000D_
<hr>_x000D_
<span class="js-content">3333</span>_x000D_
<button class="js-copy">Copy</button>
_x000D_
_x000D_
_x000D_

Older browser support:

_x000D_
_x000D_
(function(){_x000D_
_x000D_
var area = document.createElement('textarea');_x000D_
document.body.appendChild( area );_x000D_
area.style.display = "none";_x000D_
_x000D_
var content = document.querySelectorAll('.js-content');_x000D_
var copy    = document.querySelectorAll('.js-copy');_x000D_
_x000D_
for( var i = 0; i < copy.length; i++ ){_x000D_
  copyOnClick(i);_x000D_
}_x000D_
_x000D_
function copyOnClick(i){_x000D_
  copy[i].addEventListener('click', function(){_x000D_
    area.style.display = "block";_x000D_
    area.value = content[i].innerText;_x000D_
    area.select();_x000D_
    document.execCommand('copy');   _x000D_
    area.style.display = "none";_x000D_
    _x000D_
    var t = this;_x000D_
    t.innerHTML = 'Cop<span style="color: red;">ied</span>';_x000D_
    setTimeout( function(){_x000D_
      t.innerHTML = "Copy"_x000D_
    }, 2000 );_x000D_
  });_x000D_
}_x000D_
_x000D_
})();
_x000D_
hr { margin: 15px 0; border: none; }
_x000D_
<span class="js-content">1111</span>_x000D_
<button class="js-copy">Copy</button>_x000D_
<hr>_x000D_
<span class="js-content">2222</span>_x000D_
<button class="js-copy">Copy</button>_x000D_
<hr>_x000D_
<span class="js-content">3333</span>_x000D_
<button class="js-copy">Copy</button>
_x000D_
_x000D_
_x000D_


<div class="form-group">
    <label class="font-normal MyText">MyText to copy</label>&nbsp;
    <button type="button" class="btn btn-default btn-xs btnCopy" data="MyText">Copy</button>
</div>


$(".btnCopy").click(function () {
        var element = $(this).attr("data");
        copyToClipboard($('.' + element));
  });

function copyToClipboard(element) {
    var $temp = $("<input>");
    $("body").append($temp);
    $temp.val($(element).text()).select();
    document.execCommand("copy");
    $temp.remove();
}

clipboard.js is a nice utility that allows copying of text or HTML data to the clipboard without use of Flash. It's very easy to use; just include the .js and use something like this:

<button id='markup-copy'>Copy Button</button>

<script>
    document.getElementById('markup-copy').addEventListener('click', function() {
        clipboard.copy({
            'text/plain': 'Markup text. Paste me into a rich text editor.',
            'text/html': '<i>here</i> is some <b>rich text</b>'
        }).then(
            function(){console.log('success'); },
            function(err){console.log('failure', err);
        });
    });
</script>

clipboard.js is also on GitHub.

Edit on Jan 15, 2016: The top answer was edited today to reference the same API in my answer posted in August 2015. The previous text was instructing users to use ZeroClipboard. Just want to be clear that I didn't yank this from jfriend00's answer, rather the other way around.


html code here

    <input id="result" style="width:300px"/>some example text
    <button onclick="copyToClipboard('result')">Copy P1</button>
    <input type="text" style="width:400px" placeholder="Paste here for test" />

JS CODE:

     function copyToClipboard(elementId) {

                      // Create a "hidden" input
                      var aux = document.createElement("input");

                      aux.setAttribute("value", document.getElementById(elementId).value);
                      // Append it to the body
                      document.body.appendChild(aux);
                      // Highlight its content
                      aux.select();
                      // Copy the highlighted text
                      document.execCommand("copy");
                      // Remove it from the body
                      document.body.removeChild(aux);
                    }

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <link href="css/index.css" rel="stylesheet" />
    <script src="js/jquery-2.1.4.min.js"></script>
    <script>
        function copy()
        {
            try
            {
                $('#txt').select();
                document.execCommand('copy');
            }
            catch(e)
            {
                alert(e);
            }
        }
    </script>
</head>
<body>
    <h4 align="center">Copy your code</h4>
    <textarea id="txt" style="width:100%;height:300px;"></textarea>
    <br /><br /><br />
    <div align="center"><span class="btn-md" onclick="copy();">copy</span></div>
</body>
</html>

It's very important that the input field does not have display: none. The browser will not select the text and therefore will not be copied. Use opacity: 0 with a width of 0px to fix the problem.


The text to copy is in text input,like: <input type="text" id="copyText" name="copyText"> and, on button click above text should get copied to clipboard,so button is like:<button type="submit" id="copy_button" data-clipboard-target='copyText'>Copy</button> Your script should be like:

<script language="JavaScript">
$(document).ready(function() {
var clip = new ZeroClipboard($("#copy_button"), {
  moviePath: "ZeroClipboard.swf"
}); 
});

</script>

For CDN files

note: ZeroClipboard.swf and ZeroClipboard.js" file should be in the same folder as your file using this functionality is, OR you have to include like we include <script src=""></script> on our pages.


As of 2020, you should use the Clipboard Api.

navigator.clipboard.writeText('text here you want to copy').then(function () {
    alert('It worked! Do a CTRL - V to paste')
}, function () {
    alert('Failure to copy. Check permissions for clipboard')
});

Here is more info about interacting with the clipboard


jQuery simple solution.

Should be triggered by user's click.

$("<textarea/>").appendTo("body").val(text).select().each(function () {
            document.execCommand('copy');
        }).remove();

you can copy an individual text apart from an HTML element's text.

        var copyToClipboard = function (text) {
            var $txt = $('<textarea />');

            $txt.val(text)
                .css({ width: "1px", height: "1px" })
                .appendTo('body');

            $txt.select();

            if (document.execCommand('copy')) {
                $txt.remove();
            }
        };

With Line Breaks (Extention of the Answer from Alvaro Montoro)

var ClipboardHelper = {

    copyElement: function ($element)
    {
       this.copyText($element.text())
    },
    copyText:function(text) // Linebreaks with \n
    {
        var $tempInput =  $("<textarea>");
        $("body").append($tempInput);
        $tempInput.val(text).select();
        document.execCommand("copy");
        $tempInput.remove();
    }
};

ClipboardHelper.copyText('Hello\nWorld');
ClipboardHelper.copyElement($('body h1').first());

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width