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.
you can just using this lib for easy realize the copy goal!
https://clipboardjs.com/
or
https://github.com/zeroclipboard/zeroclipboard
http://zeroclipboard.org/
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:
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.
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:
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. Useopacity: 0
with a width of 0px to fix the problem.html code here
JS CODE:
Both will works like a charm :),
JAVASCRIPT:
Also in html,
JQUERY: https://paulund.co.uk/jquery-copy-clipboard