Working "Copy to Clipboard" function doesn't work when called in bootstrap modal
document.execCommand('copy'); functionality depends on trusted events. If a event needs to be trusted then the target element should also have a proper focus.
Try setting the focus on the textElement and set it to the modal after you remove it from the text element. this should solve the problem
function copytext(text) {
var textField = document.createElement('textarea');
textField.innerText = text;
document.body.appendChild(textField);
textField.select();
textField.focus(); //SET FOCUS on the TEXTFIELD
document.execCommand('copy');
textField.remove();
console.log('should have copied ' + text);
ajax-error.focus(); //SET FOCUS BACK to MODAL
}
In short: as the modal has
tabindex="-1"
the.focus()
will only work in Chrome. For a cross-browser solution, you have to insert the textarea into the DOM as a descendant of the modal.
The key is, that the textarea has to be the document.activeElement
when the copy command is executed. In other words, it has to have focus. This could be achieved by calling .focus()
on it, however in your specific case the click event happens within a modal with a tabindex="-1"
already in focus. At the time of writing in this scenario the .focus()
method will work in Chrome only. In other browsers tabindex="-1"
will prevent the textarea from getting focused, unless it is a descendant node of the modal.
Therefore the solution below creates the textarea when it always can have focus, as a sibling of the clicked element:
$(document).ready(function(){
$(document).on('click', '#copy-btn', function(){
copytext('dferenc tested this', this);
})
});
function copytext(text, context) {
var textField = document.createElement('textarea');
textField.innerText = text;
if (context) {
context.parentNode.insertBefore(textField, context);
} else {
document.body.appendChild(textField);
}
textField.select();
document.execCommand('copy');
// Let `.remove()` also work with older IEs
textField.parentNode.removeChild(textField);
console.log('should have copied ' + text);
}