How can I copy the content of an div
(or any element) to the clipboard using only JavaScript/jQuery without using Flash?
For example, if I have this code:
<p id="mi_parrafo">
Texto que quiero copiar
</p>
<button>Copiar al portapapeles</button>
What should I do so that, after pressing the button, when I press Ctr+ Vthe content is pasted inside the label marked as #mi_parrafo
?
There is at least one way to achieve this without using Flash: using the
copy
. This command will copy to the clipboard the text that is selected on the page at the time it is executed.So you can create a small function that:
document.execCommand("copy")
.Then the content of the selected item will be on the clipboard. The code would be like this:
The main problem with this solution is that not all browsers support this command , although it can be used in the main ones from:
A working demo of the code:
An equivalent version can also be created using jQuery:
Which works similarly to the example above, although some bugs have been reported in Safari for Mac and Chrome 64-bit (see the comments in the original source link for more details).
Source: Original answer on StackOverflow site .
EXTENSION: COPY KEEPING STYLES
In another question on StackOverflow in Spanish , a user commented that the formatting/styles of the text were not copied. This is because in the code above it uses
input text
to copy the content of the element, so the HTML code is "lost" (it is interpreted literally instead of as HTML). If instead of using aninput
we use andiv
editable, the formatting is not lost and can be copied/pasted with styles:Just to complement you could take a look at the clipboard.js library , which as @Alvaro mentions makes use of execCommand so according to the library page it says that it works in Chrome 42+, Firefox 41+, IE 9+ and Opera 29+.
It doesn't work for Safari, but when you try it on an iPad, it selects the text from
input
while showing you the native option to copy it.The difference is in the ease of use , since with little time and effort you can copy the content you want, the following code copies the content of a
input
, but you can also copy/cut the content of another element ( button, div, etc. ).it will be the same as the other guy above but instead of an input a text area so that the indentation respects you if you have more than one line
Hello I was wondering if it is possible to encapsulate what one wants to copy.