486

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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Dishan TD
  • 7,118
  • 7
  • 21
  • 37
  • Refer to http://stackoverflow.com/questions/400212/how-to-copy-to-the-clipboard-in-javascript – SquareCat Mar 22 '14 at 17:55
  • Trello has a clever way to do this without flash: http://stackoverflow.com/questions/17527870/how-does-trello-access-the-users-clipboard – Paul Schreiber Oct 30 '14 at 15:37
  • Refer this, http://stackoverflow.com/questions/22581345/click-button-copy-to-clipboard-using-jquery#30905277 got expected solution using Pure JavaScript – Vignesh Chinnaiyan Jun 17 '16 at 10:14
  • @MichaelScheper - some users are even smart enough to notice that my comment, and most of the answers here, were posted over four years ago, when zeroclipboard, which is based on a small flash app, was the only cross-browser viable option to work with the clipboard, and the goto solution. Today all modern browsers support this natively, so it's no longer an issue, but that wasn't the case in 2014 – adeneo May 24 '18 at 06:02
  • @adeneo: Sure, but not all users are that 'smart', and your comment still has two upvotes. – Michael Scheper May 30 '18 at 16:58
  • @MichaelScheper even users that aren't that 'smart' won't have a problem with my comment, the old flash-based ZeroClipboard has been removed, and the link won't get even the smartest of users anything flash-based to download. Next time, before you criticise, think about the fact that the web hasn't always been the way it is today, it was quite different just a few years ago. – adeneo May 31 '18 at 00:43
  • @adeneo: Happy to hear that first part; it addresses my concern. I'm sorry that my comment came across as overly critical, but it doesn't imply that yours was _always_ wrong… I'm a bit surprised that your reaction seems so hostile, TBH. I'll admit, though, that I've never been a fan of Flash, and the attitude that it's a quick-fix that works everywhere is a bugbear, especially for mobile browsers! And I'm actually quite aware of how the web's changed—I've been doing web development for over 20 years. So I hope you, too, will mention it whenever StackOverflow comments become outdated. – Michael Scheper Jun 07 '18 at 21:38
  • @MichaelScheper - your comment didn't come across as overly critical, it came across as completely misplaced and condescending. Commenting *"Seriously no ... flash is evil, users know better .."* four years later, seems completely redundant, we all know noone uses flash anymore, it's not supported on all platforms etc, and the answers below are updated to reflect that. However, when those answers, and my comment was first posted, flash was the only viable answer to this question, and as such my comment stands, if only for historical purposes. There's absolutely no need to remove it, – adeneo Jun 09 '18 at 19:34
  • you don't need JQuery, you need Clipboard-polyfill library. – Yevgeniy Afanasyev Jun 25 '18 at 03:52
  • try this solution [simple copy in jquery](https://stackoverflow.com/a/65474415/5295519) – Vajiheh habibi Dec 28 '20 at 08:29

22 Answers22

748

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:

function copyToClipboard(element) {
  var $temp = $("<input>");
  $("body").append($temp);
  $temp.val($(element).text()).select();
  document.execCommand("copy");
  $temp.remove();
}
<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" />

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):

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);

}
<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" />

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:

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);
}
#target {
  width:400px;
  height:100px;
  border:1px solid #ccc;
}
<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>

And in jQuery, it would be like this:

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();
}
#target {
  width:400px;
  height:100px;
  border:1px solid #ccc;
}
<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>
Ehsan88
  • 2,816
  • 4
  • 22
  • 44
Alvaro Montoro
  • 23,383
  • 6
  • 47
  • 81
  • 5
    strange ... here it works, but I cannot get to work it locally 0o jquery-1.11.3 Chrome 43.0.2357.130 (64-bit) – madzohan Jun 25 '15 at 15:01
  • I've removed $("#temp").remove(); and perform in console (after copyToClipboard triggered) **$("#temp").val($('body').text()).select();** > [​] **document.execCommand("copy");** > false – madzohan Jun 25 '15 at 15:41
  • seems **select()** problem because **document.execCommand("copy")** works after selecting some text on page manually – madzohan Jun 25 '15 at 15:43
  • nope it is only one (after **remove()** $('#temp') -> nothing) – madzohan Jun 25 '15 at 15:47
  • This is strange. Does it work if you assign it a string instead of doing `$('body').text()`? – Alvaro Montoro Jun 25 '15 at 15:56
  • nope it doesn't work ... looking for another way to select – madzohan Jun 25 '15 at 16:09
  • 2
    @madzohan Ok, I was able to reproduce the issue. It is weird because I was only able to reproduce it on local (file://) on 64-bit Chrome. I also found a quick solution that works for me: using plain JavaScript instead of jQuery. I will update the answer with that code. Please check it and let me know if it works for you. – Alvaro Montoro Jun 25 '15 at 16:30
  • thanks, but anyway it doesn't work :D works only in chain document.execCommand("SelectAll"); document.execCommand("Copy"); maybe you know how to select window.location.href without any temp manipulations? – madzohan Jun 25 '15 at 16:46
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/81561/discussion-between-alvaro-montoro-and-madzohan). – Alvaro Montoro Jun 25 '15 at 16:50
  • 1
    FWIW - document.execCommand("copy") returns a boolean (IE, Chrome, Safari) indicating whether the copy was successful. It could be used to display an error message on failure. Firefox throws an exception on failure (in v39 at least), requiring a try/catch to handle the error. – PointZeroTwo Jul 27 '15 at 17:41
  • 1
    The jquery version can be improved slightly to not use a "#temp" id, which could conflict with something else on the page. Start by creating the temporary input object with: var $temp = $("");, then append $temp to the page, and call $temp.remove() to remove it. See https://jsfiddle.net/tvkrdjs8/1/ (also includes some error handling around execCommand). – PointZeroTwo Jul 27 '15 at 17:59
  • 3
    This didn't work for me until I made sure that aux was visible on the page by adding the following lines: `aux.style.position = "fixed";` `aux.style.top = 0;` above the `appendChild` call. – ariscris Oct 07 '15 at 18:15
  • @ariscris what browser are you using when you get those errors? – Alvaro Montoro Oct 07 '15 at 18:24
  • Both IE 11 and Chrome 45. The snippet here works, it's something specific to our app. – ariscris Oct 07 '15 at 20:01
  • It's a good answer, just want to add that there's no guarantee that `document.execCommand()` will return `false` or throw an exception if copying is not allowed. For instance, I'm testing it on IE11 and if I disallow copying (from its security UI) the method still returns `true` even though nothing is copied to the clipboard. – c00000fd Oct 21 '15 at 03:02
  • This should be the accepted answer, surely? The current accepted answer is (an extended and well explained) "nope", but this shows it actually can be done, and in only a few lines of js. – Sinister Beard Jan 15 '16 at 12:32
  • Have you found any way to make the copy to clipboard work in Safari yet? – jfriend00 Jan 15 '16 at 18:03
  • @jfriend00 No, I haven't found solution for Safari. – Alvaro Montoro Jan 15 '16 at 19:35
  • I think it would be better to use – user3047190 Feb 15 '16 at 15:10
  • 1
    Works fine, thank you! It is important to mention that this works only immediately on certain events (e.g. click). I tried to run that code in an ajax-callback and it wouldn't work. – molerat Jul 28 '16 at 23:17
  • I have a long table of students and you can click a button in each row that copies data into your clipboard. Every time I do that, the browser scrolls to the bottom of the page. Is there a way to avoid this? – molerat Jul 28 '16 at 23:20
  • Does this work on firefox 52? I tried both versions to copy to clipboard on a span id and I am unable to get the text for copy using this. Are there any tweaks? – user2868864 Mar 26 '17 at 16:44
  • 8
    The original jQuery implementation fails to preserve line breaks, because it is using an INPUT element. Using a TEXTAREA instead solves this. – thomasfuchs Jun 10 '17 at 14:20
  • @thomasfuchs I added a fix for that in an edit for vanilla JS but forgot jQuery. I need to update the jQuery version. Thanks for pointing it out – Alvaro Montoro Jun 10 '17 at 14:23
  • Thanks, you saved me a lot of time. I used the code in the "COPY KEEPING THE TEXT FORMAT" part and it worked with me except I had to copy the `outterHTML` of the element not the `innerHTML` so elements like '' should be copied also with it's '
    ' wrapper, not to start the copy from it's innerHTML ''
    – Accountant م Jun 20 '17 at 12:22
  • All right, works like a charm, and I agree, this should be used as the correct answer. I'm also using a TEXTAREA because in my case (I have code snippets) I need the lines to be broken correctly. Nice work, though, this is exactly what I wanted! I'm probably going to add a popup or something to give feedback on the copy, but that's beyond the scope of this answer. Thank you a lot! – Gwyneth Llewelyn Jul 06 '17 at 11:00
  • @JennyO'Reilly Thanks for the feedback. I'll check it later today and check what's wrong. – Alvaro Montoro Nov 06 '17 at 17:45
  • Could it be that Edge copies the content of the entire page, instead of only the content from the div to the clipboard? I also tried the solution suggested here: https://stackoverflow.com/questions/12243898/how-to-select-all-text-in-contenteditable-div but it has the same effect. – Krisztián Balla Nov 17 '17 at 11:43
  • Unfortunately the workaround with the contenteditable div is no longer working in Internet Explorer version 11.125.16299.0 (Updateversion: 11.0.49 - KB4052978). I tried it on several computers. :-( I created a separate question for this here: https://stackoverflow.com/questions/47907503/document-execcommandcopy-no-longer-working-in-internet-explorer-11 – Krisztián Balla Dec 20 '17 at 13:55
  • Good news. I found a solution for the problem. Please see the answer to the question I've just linked to. – Krisztián Balla Dec 20 '17 at 15:11
  • No reason to name the variable as $temp, looks confuse when use jQuery. Just use "temp", since $ is mostly related to jQuery. – Arvy Nov 13 '20 at 20:35
  • I'm using the jquery code you gave for keeping the html formatting, and using it in wordpress, but the .focus() is causing it to scroll to the bottom of the page on click. Do you know how to stop that? – Jon Fergus Dec 11 '20 at 20:28
  • Uncaught Error: Syntax error, unrecognized expression – fdrv Feb 06 '21 at 22:38
  • I use `$(this).append($temp)` instead of `$("body").append($temp)`, because the original method does not work on modals (chrome). – Amir Hossein Mar 28 '21 at 20:04
505

Edit as of 2016

As of 2016, you can now copy text to the clipboard in most browsers because most browsers have the ability to programmatically copy a selection of text to the clipboard using document.execCommand("copy") that works off a selection.

As with some other actions in a browser (like opening a new window), the copy to clipboard can only be done via a specific user action (like a mouse click). For example, it cannot be done via a timer.

Here's a code example:

document.getElementById("copyButton").addEventListener("click", function() {
    copyToClipboard(document.getElementById("copyTarget"));
});

function copyToClipboard(elem) {
   // create hidden text element, if it doesn't already exist
    var targetId = "_hiddenCopyText_";
    var isInput = elem.tagName === "INPUT" || elem.tagName === "TEXTAREA";
    var origSelectionStart, origSelectionEnd;
    if (isInput) {
        // can just use the original source element for the selection and copy
        target = elem;
        origSelectionStart = elem.selectionStart;
        origSelectionEnd = elem.selectionEnd;
    } else {
        // must use a temporary form element for the selection and copy
        target = document.getElementById(targetId);
        if (!target) {
            var target = document.createElement("textarea");
            target.style.position = "absolute";
            target.style.left = "-9999px";
            target.style.top = "0";
            target.id = targetId;
            document.body.appendChild(target);
        }
        target.textContent = elem.textContent;
    }
    // select the content
    var currentFocus = document.activeElement;
    target.focus();
    target.setSelectionRange(0, target.value.length);
    
    // copy the selection
    var succeed;
    try {
       succeed = document.execCommand("copy");
    } catch(e) {
        succeed = false;
    }
    // restore original focus
    if (currentFocus && typeof currentFocus.focus === "function") {
        currentFocus.focus();
    }
    
    if (isInput) {
        // restore prior selection
        elem.setSelectionRange(origSelectionStart, origSelectionEnd);
    } else {
        // clear temporary content
        target.textContent = "";
    }
    return succeed;
}
input {
  width: 400px;
}
<input type="text" id="copyTarget" value="Text to Copy"> <button id="copyButton">Copy</button><br><br>
<input type="text" placeholder="Click here and press Ctrl-V to see clipboard contents">

Here's a little more advanced demo: https://jsfiddle.net/jfriend00/v9g1x0o6/

And, you can also get a pre-built library that does this for you with clipboard.js.


Old, historical part of answer

Directly copying to the clipboard via JavaScript is not permitted by any modern browser for security reasons. The most common workaround is to use a Flash capability for copying to the clipboard that can only be triggered by a direct user click.

As mentioned already, ZeroClipboard is a popular set of code for managing the Flash object to do the copy. I've used it. If Flash is installed on the browsing device (which rules out mobile or tablet), it works.


The next most common work-around is to just place the clipboard-bound text into an input field, move the focus to that field and advise the user to press Ctrl + C to copy the text.

Other discussions of the issue and possible work-arounds can be found in these prior Stack Overflow posts:


These questions asking for a modern alternative to using Flash have received lots of question upvotes and no answers with a solution (probably because none exist):


Internet Explorer and Firefox used to have non-standard APIs for accessing the clipboard, but their more modern versions have deprecated those methods (probably for security reasons).


There is a nascent standards effort to try to come up with a "safe" way to solve the most common clipboard problems (probably requiring a specific user action like the Flash solution requires), and it looks like it may be partially implemented in the latest versions of Firefox and Chrome, but I haven't confirmed that yet.

Community
  • 1
  • 1
jfriend00
  • 580,699
  • 78
  • 809
  • 825
  • @DishanTD - I added a number of other references and info about the latest HTML5 spec. – jfriend00 Mar 22 '14 at 19:21
  • Interestingly: Google Docs seems to do this somehow (try to "share" a document, and it automatically copies the link to your clipboard) – wxs Apr 09 '15 at 22:05
  • Another interesting fun fact. I found that you can open console on a Google Docs page and input document.execCommand('copy') and you will get 'true' back. (I disabled all extensions and even tried in incognito mode.) Try it on another site and 'false.' – Ecropolis Apr 23 '15 at 18:13
  • 1
    clipboard.js was just added to this edited post. It's a good utility that I included as an answer to this question in August 2015. – a coder Jan 15 '16 at 19:26
  • 1
    @acoder - Clipboard support has been changing regularly. For example, Firefox only recently (late 2015) enabled `document.execCommand("copy")` in enough circumstances to rely on using it for this. So, I am endeavoring to keep my answer up to date (which was originally authored almost 2 years ago). We still do not yet have a reliable solution for Safari other than pre-selecting the text and telling the user to manually press Ctrl+C, but at least progress is being made elsewhere. – jfriend00 Jan 15 '16 at 19:30
  • Updated the code to not create the temporary DOM object if the passed in DOM element to copy from is the type that we can copy directly from. Also, save/restore the current focus and selection so that is not disturbed by calling the copy function. – jfriend00 Jan 18 '16 at 16:34
  • Just what I needed, a reply in 2016 with the new featured added to js, tnx buddie! – isabelle martz Jan 26 '16 at 17:22
  • 1
    Here is a link to support for the Clipboard APIs: http://caniuse.com/#feat=clipboard – L84 Feb 23 '16 at 19:22
  • 2
    FYI, per [this set of Safari release notes](https://developer.apple.com/library/prerelease/content/releasenotes/General/WhatsNewInSafari/Articles/Safari_10_0.html), it appears that Safari 10 does now support `document.execCommand("copy")` so this code should now work in Safari 10. – jfriend00 Jun 24 '16 at 16:25
  • Impressive answer. The biggest and most comprehensive answer I have seen. Hats off to you sir or mam. – Mr.Glaurung Mar 13 '17 at 07:22
  • @jfriend00, what is the license of this snippet? – Sebastian Jun 02 '17 at 03:02
  • 1
    @sebastiangodelet - public domain. – jfriend00 Jun 02 '17 at 04:09
  • DOM actually scrolls up the page while Copying. Please can you fix it? – jackkorbin Jun 20 '17 at 07:13
  • Why don't you remove the target element when your done? – mmm Sep 01 '17 at 14:52
  • @momomo - You could remove it when done if you wanted. I chose to leave it to save time on future copy operations. It is hidden so will not really affect anything. – jfriend00 Sep 01 '17 at 15:06
  • Yes, I did. The dom tree should not get clogged up unnecessary. Imagine all libraries did that. There's not much saving anyway. – mmm Sep 01 '17 at 15:23
  • @momomo - One invisible extra DOM element that is not being used does not "clog" up anything. Even if you had 20, it wouldn't be significant. But, you're perfectly welcome to remove it when done. – jfriend00 Sep 01 '17 at 15:24
38

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.

Community
  • 1
  • 1
a coder
  • 6,796
  • 19
  • 77
  • 121
35

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;" />
Nadav
  • 875
  • 9
  • 12
  • doesn’t seem to work on ipad, haven’t tested but a suggested solution is here: https://stackoverflow.com/a/34046084 – user1063287 Sep 27 '18 at 14:16
  • That worked for me, but if the text to be copied contains carriage returns then you can just as well use a textarea instead. – Alex Jun 06 '20 at 15:33
16

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());
12

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

$(function(){
  new Clipboard('.copy-text');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/clipboard.js/1.5.12/clipboard.min.js"></script>

<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>

<a class="copy-text" data-clipboard-target="#content" href="#">copy Text</a>
Amgad
  • 315
  • 3
  • 8
10

As of 2021, 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

thalacker
  • 878
  • 11
  • 30
9
<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();
}
MD. Khairul Basar
  • 4,237
  • 11
  • 38
  • 52
Nayan Hodar
  • 460
  • 6
  • 10
  • Nice workaround. Maybe add `.addClass("hidden")` to the `` tag to have it never shown up in browser? – Roland Jan 31 '18 at 11:01
7

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

mehdipayervand
  • 301
  • 3
  • 7
keivan kashani
  • 784
  • 8
  • 10
6

jQuery simple solution.

Should be triggered by user's click.

$("<textarea/>").appendTo("body").val(text).select().each(function () {
            document.execCommand('copy');
        }).remove();
holden321
  • 939
  • 1
  • 11
  • 29
5
<!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>
Ujjwal Kumar Gupta
  • 1,665
  • 1
  • 14
  • 29
5

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.

david
  • 3,201
  • 9
  • 26
  • 40
Mark Lancaster
  • 172
  • 2
  • 4
4

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'));
                    });
Umer Farook
  • 268
  • 2
  • 5
4

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:

//Pure javascript implementation:
document.getElementById("copyUsingPureJS").addEventListener("click", function() {
  copyUsingPureJS(document.getElementById("copyTarget"));
  alert("Text Copied to Clipboard Using Pure Javascript");
});

function copyUsingPureJS(element_id) {
  element_id.setAttribute("contentEditable", true);
  element_id.setAttribute("onfocus", "document.execCommand('selectAll',false,null)");
  element_id.focus();
  document.execCommand("copy");
  element_id.removeAttribute("contentEditable");
  
}

//Jquery:
$(document).ready(function() {
  $("#copyUsingJquery").click(function() {
    copyUsingJquery("#copyTarget");
  });
 

  function copyUsingJquery(element_id) {
    $(element_id).attr("contenteditable", true)
      .select()
      .on("focus", function() {
        document.execCommand('selectAll', false, null)
      })
      .focus()
    document.execCommand("Copy");
    $(element_id).removeAttr("contenteditable");
     alert("Text Copied to Clipboard Using jQuery");
  }
});
#copyTarget {
  width: 400px;
  height: 400px;
  border: 1px groove gray;
  color: navy;
  text-align: center;
  box-shadow: 0 4px 8px 0 gray;
}

#copyTarget h1 {
  color: blue;
}

#copyTarget h2 {
  color: red;
}

#copyTarget h3 {
  color: green;
}

#copyTarget h4 {
  color: cyan;
}

#copyTarget h5 {
  color: brown;
}

#copyTarget h6 {
  color: teal;
}

#pasteTarget {
  width: 400px;
  height: 400px;
  border: 1px inset skyblue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="copyTarget">
  <h1>Heading 1</h1>
  <h2>Heading 2</h2>
  <h3>Heading 3</h3>
  <h4>Heading 4</h4>
  <h5>Heading 5</h5>
  <h6>Heading 6</h6>
  <strong>Preserve <em>formatting</em></strong>
  <br/>
</div>

<button id="copyUsingPureJS">Copy Using Pure JavaScript</button>
<button id="copyUsingJquery">Copy Using jQuery</button>
<br><br> Paste Here to See Result
<div id="pasteTarget" contenteditable="true"></div>
Jeffrey Kilelo
  • 156
  • 1
  • 4
2

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.

Suhaib Janjua
  • 3,273
  • 13
  • 52
  • 68
2

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.

xgqfrms
  • 5,516
  • 1
  • 37
  • 42
2

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.

Yevgeniy Afanasyev
  • 27,544
  • 16
  • 134
  • 147
1

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);
                    }
li bing zhao
  • 1,256
  • 12
  • 11
1

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();
            }
        };
Alper Ebicoglu
  • 6,488
  • 1
  • 34
  • 39
0

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

(function(){

/* Creating textarea only once, but not each time */
let area = document.createElement('textarea');
document.body.appendChild( area );
area.style.display = "none";

let content = document.querySelectorAll('.js-content');
let copy    = document.querySelectorAll('.js-copy');

for( let i = 0; i < copy.length; i++ ){
  copy[i].addEventListener('click', function(){
    area.style.display = "block";
    /* because the classes are paired, we can use the [i] index from the clicked button,
    to get the required text block */
    area.value = content[i].innerText;
    area.select();
    document.execCommand('copy');   
    area.style.display = "none";

    /* decorative part */
    this.innerHTML = 'Cop<span style="color: red;">ied</span>';
    /* arrow function doesn't modify 'this', here it's still the clicked button */
    setTimeout( () => this.innerHTML = "Copy", 2000 );
  });
}

})();
hr { margin: 15px 0; border: none; }
<span class="js-content">1111</span>
<button class="js-copy">Copy</button>
<hr>
<span class="js-content">2222</span>
<button class="js-copy">Copy</button>
<hr>
<span class="js-content">3333</span>
<button class="js-copy">Copy</button>

Older browser support:

(function(){

var area = document.createElement('textarea');
document.body.appendChild( area );
area.style.display = "none";

var content = document.querySelectorAll('.js-content');
var copy    = document.querySelectorAll('.js-copy');

for( var i = 0; i < copy.length; i++ ){
  copyOnClick(i);
}

function copyOnClick(i){
  copy[i].addEventListener('click', function(){
    area.style.display = "block";
    area.value = content[i].innerText;
    area.select();
    document.execCommand('copy');   
    area.style.display = "none";
    
    var t = this;
    t.innerHTML = 'Cop<span style="color: red;">ied</span>';
    setTimeout( function(){
      t.innerHTML = "Copy"
    }, 2000 );
  });
}

})();
hr { margin: 15px 0; border: none; }
<span class="js-content">1111</span>
<button class="js-copy">Copy</button>
<hr>
<span class="js-content">2222</span>
<button class="js-copy">Copy</button>
<hr>
<span class="js-content">3333</span>
<button class="js-copy">Copy</button>
OPTIMUS PRIME
  • 1,191
  • 7
  • 19
0
<p style="color:wheat;font-size:55px;text-align:center;">How to copy a TEXT to Clipboard on a Button-Click</p>
    
    <center>
    <p id="p1">Hello, I'm TEXT 1</p>
    <p id="p2">Hi, I'm the 2nd TEXT</p><br/>
    
    <button onclick="copyToClipboard('#p1')">Copy TEXT 1</button>
    <button onclick="copyToClipboard('#p2')">Copy TEXT 2</button>
      
    </center>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
<script>
    function copyToClipboard(element) {
      var $temp = $("<input>");
      $("body").append($temp);
      $temp.val($(element).text()).select();
      document.execCommand("copy");
      $temp.remove();
    }
</script>
Diako Hasani
  • 698
  • 5
  • 13
-1

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

Harshal Lonare
  • 2,198
  • 25
  • 29