1function copyToClipboard(text) {
2 const elem = document.createElement('textarea');
3 elem.value = text;
4 document.body.appendChild(elem);
5 elem.select();
6 document.execCommand('copy');
7 document.body.removeChild(elem);
8}
1function copyToClipboard(value) {
2 navigator.clipboard.writeText(value)
3}
1// Since Async Clipboard API is not supported for all browser!
2function copyTextToClipboard(text) {
3 var textArea = document.createElement("textarea");
4 textArea.value = text
5 document.body.appendChild(textArea);
6 textArea.focus();
7 textArea.select();
8
9 try {
10 var successful = document.execCommand('copy');
11 var msg = successful ? 'successful' : 'unsuccessful';
12 console.log('Copying text command was ' + msg);
13 } catch (err) {
14 console.log('Oops, unable to copy');
15 }
16
17 document.body.removeChild(textArea);
18}
1function copyToClipboard(text) {
2 var input = document.body.appendChild(document.createElement("input"));
3 input.value = text;
4 input.focus();
5 input.select();
6 document.execCommand('copy');
7 input.parentNode.removeChild(input);
8}
1var copyTextareaBtn = document.querySelector('.js-textareacopybtn');
2
3copyTextareaBtn.addEventListener('click', function(event) {
4 var copyTextarea = document.querySelector('.js-copytextarea');
5 copyTextarea.focus();
6 copyTextarea.select();
7
8 try {
9 var successful = document.execCommand('copy');
10 var msg = successful ? 'successful' : 'unsuccessful';
11 console.log('Copying text command was ' + msg);
12 } catch (err) {
13 console.log('Oops, unable to copy');
14 }
15});
16
17////html code below
18<p>
19 <button class="js-textareacopybtn" style="vertical-align:top;">Copy Textarea</button>
20 <textarea class="js-copytextarea">Hello I'm some text</textarea>
21</p>
1var copy = document.querySelectorAll(".copy");
2
3for (const copied of copy) {
4 copied.onclick = function() {
5 document.execCommand("copy");
6 };
7 copied.addEventListener("copy", function(event) {
8 event.preventDefault();
9 if (event.clipboardData) {
10 event.clipboardData.setData("text/plain", copied.textContent);
11 console.log(event.clipboardData.getData("text"))
12 };
13 });
14};