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?
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.
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'));
});
jQuery simple solution.
Should be triggered by user's click.
$("<textarea/>").appendTo("body").val(text).select().each(function () {
document.execCommand('copy');
}).remove();
<!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>
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
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:
How do I copy to the clipboard in JavaScript?
How to copy text to the client's clipboard using jQuery?
How can you copy to clipboard without Flash?
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):
HTML5 alternative to flash-based ZeroClipboard for safe copying of data to clipboard?
Copy to clipboard without Flash
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.