A handy JavaScript function that allows you to copy text from an input field to your clipboard when you click a button. Here's how it works:
<script type="text/javascript">
(function () {
'use strict';
// Listen for click events
document.body.addEventListener('click', copy, true);
// Event handler
function copy(e) {
// Find target element
var
t = e.target,
c = t.dataset.copytarget,
inp = (c ? document.querySelector(c) : null);
// Check if element is selectable
if (inp && inp.select) {
// Select text
inp.select();
try {
// Copy text
document.execCommand('copy');
inp.blur();
}
catch (err) {
alert('please press Ctrl/Cmd+C to copy');
}
}
}
})();
</script>
Usage example:
<button id="CopyTextBtn" autofocus
type="submit"
class="uui-button lime-green"
data-copytarget="#ClientsURL"
ng-click="closeThisDialog('Cancel')">
Copy
</button>
I attempted to implement this functionality using a directive in my app:
appModule.directive('data-copytarget', function () {
return {
scope: {},
link: function (scope, element)
{
// Listen for click events
document.body.addEventListener('click', copy, true);
// Event handler
function copy(e) {
// Find target element
var
t = e.target,
c = t.dataset.copytarget,
inp = (c ? document.querySelector(c) : null);
// Check if element is selectable
if (inp && inp.select) {
// Select text
inp.select();
try {
// Copy text
document.execCommand('copy');
inp.blur();
}
catch (err) {
alert('please press Ctrl/Cmd+C to copy');
}
}
}
}
};
});
Unfortunately, I encountered issues with this implementation and it did not work as expected.