1function copyToClipboard(text) {
2 var dummy = document.createElement("textarea");
3 // to avoid breaking orgain page when copying more words
4 // cant copy when adding below this code
5 // dummy.style.display = 'none'
6 document.body.appendChild(dummy);
7 //Be careful if you use texarea. setAttribute('value', value), which works with "input" does not work with "textarea". – Eduard
8 dummy.value = text;
9 dummy.select();
10 document.execCommand("copy");
11 document.body.removeChild(dummy);
12}
13copyToClipboard('hello world')
14copyToClipboard('hello\nworld')
1<head><script>
2function copyToCliBoard() {
3 var copyText = document.getElementById("myInput");
4 copyText.select();
5 copyText.setSelectionRange(0, 99999); /* For mobile devices */
6 document.execCommand("copy");
7 alert("Copied the text: " + copyText.value);
8}
9</script></head>
10
11<body>
12<input type="text" value="Hello World" id="myInput">
13<button onclick="copyToCliBoard()">Copy text</button>
14</body>
1function copy() {
2 var copyText = document.querySelector("#input");
3 copyText.select();
4 document.execCommand("copy");
5}
6
7document.querySelector("#copy").addEventListener("click", copy);
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}
1 var dummyContent = "this is to be copied to clipboard";
2 var dummy = $('<input>').val(dummyContent).appendTo('body').select()
3 document.execCommand('copy')
4