I have tried all the possible cases but none of them worked. So instead of using clipboard i just did some js tricks.
first select the text which you want to copy.
document.querySelector('#txtCopy').select();
but this code will work only if your element is textbox. So how to select if you want to select content inside div or span etc. Well you can use the below function to do that -
function selectText(element) {
if (/INPUT|TEXTAREA/i.test(element.tagName)) {
element.focus();
if (element.setSelectionRange) {
element.setSelectionRange(0, element.value.length);
} else {
element.select();
}
return;
}
if (window.getSelection) { // All browsers, except IE <=8
window.getSelection().selectAllChildren(element);
} else if (document.body.createTextRange) { // IE <=8
var range = document.body.createTextRange();
range.moveToElementText(element);
range.select();
}
}
Now we need to copy the selected text -
document.execCommand('copy');
Now you can see that text is copied.
Sometimes you need to deSelect all the text after copying. In that case - you can use below function to deSelect -
function deselectAll() {
var element = document.activeElement;
if (element && /INPUT|TEXTAREA/i.test(element.tagName)) {
if ('selectionStart' in element) {
element.selectionEnd = element.selectionStart;
}
element.blur();
}
if (window.getSelection) { // All browsers, except IE <=8
window.getSelection().removeAllRanges();
} else if (document.selection) { // IE <=8
document.selection.empty();
}
}
Hope this works for you.