How to js copy to clipboard
Toggle class name on click in jQuery
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>
<div class="tooltip">
<button onclick="myFunction()" onmouseout="outFunc()">
<span class="tooltiptext" id="myTooltip">Copy to clipboard</span>
Copy text
</button>
</div>
<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;
}
JavaScript
function copyTextToClipboard(text) {
try {
var widgetId = "uiClipboard_InputId",
textArea = $('<textarea></textarea>')
.attr('id', widgetId)
.val(text);
$('body').append(textArea);
textArea.focus();
textArea.select();
var successful = document.execCommand("copy");
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copying text command was ' + msg);
$('#' + widgetId).remove();
var tooltip = $("#myTooltip");
tooltip.html("Copied: " + textArea.val());
} catch (err) {
console.log('Oops, unable to copy' + err);
}
}
function myFunction() {
var InTxt = $('#myInput').val();
console.log(InTxt.indexOf('\n') > 0);
copyTextToClipboard(InTxt);
}
function outFunc() {
var tooltip = $("#myTooltip");
tooltip.html("Copy to clipboard");
}