copy and paste to textarea
by Seungrae Lee
HTML
<p>Click on the button to copy the text from the text field. Try to paste the text (e.g. ctrl+v) afterwards in a different window, to see the effect.</p>
<textarea id="myInput" rows="2">
Hello
There!
</textarea>
<textarea id="uiClipboard_InputId">
</textarea>
<div class="tooltip">
<button onclick="myFunction()" onmouseout="outFunc()">
<span class="tooltiptext" id="myTooltip">Copy to clipboard</span>
Copy text
</button>
<button onclick="paste()">
Paste text
</button>
</div>
<textarea id="myOutput" rows="2">
</textarea>
<p>The document.execCommand() method is not supported in IE8 and earlier.</p>
CSS
.tooltip {
position: relative;
display: inline-block;
}
.tooltip .tooltiptext {
visibility: hidden;
width: 140px;
background-color: #555;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 5px;
position: absolute;
z-index: 1;
bottom: 150%;
left: 50%;
margin-left: -75px;
opacity: 0;
transition: opacity 0.3s;
}
.tooltip .tooltiptext::after {
content: "";
position: absolute;
top: 100%;
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: #555 transparent transparent transparent;
}
.tooltip:hover .tooltiptext {
visibility: visible;
opacity: 1;
}
#uiClipboard_InputId {
display: none;
}
JavaScript
function myFunction() {
var InTxt = $('myInput').value;
console.log(InTxt.indexOf('\n') > 0);
copyTextToClipboard(InTxt);
}
function copyTextToClipboard(text) {
try {
var widgetId = "uiClipboard_InputId",
textArea = $(widgetId);
textArea.value = text;
var tooltip = $("myTooltip");
tooltip.innerHTML = "Copied: " + textArea.value;
} catch (err) {
console.log('Oops, unable to copy' + err);
}
}
function outFunc() {
var tooltip = $("myTooltip");
tooltip.innerHTML = "Copy to clipboard";
}
function paste() {
try {
var pasteArea = $('myOutput'),
clipboard = $('uiClipboard_InputId');
pasteArea.value = clipboard.value;
clipboard.value = "";
} catch (err) {
console.log('Oops, unable to paste' + err);
}
}