how to create a list and copy to clipboard using javascript code example
Example 1: javascript text to clipboard
function copyToClipboard(text) {
const elem = document.createElement('textarea');
elem.value = text;
document.body.appendChild(elem);
elem.select();
document.execCommand('copy');
document.body.removeChild(elem);
}
Example 2: js copy to clipboard cross browser
function copy2clipboard( text, callback ) {
if ( navigator.clipboard ) {
navigator.clipboard.writeText( text )
.then( function(){
callback && callback();
}).catch( function( err ){
errorMessage( err );
});
}
else {
var textArea = document.createElement( 'textarea' );
textArea.setAttribute( 'style', 'width:1px;border:0;opacity:0;' );
document.body.appendChild( textArea );
textArea.value = text;
textArea.select();
try {
var isCopied = document.execCommand('copy');
isCopied ? ( callback && callback() ) : errorMessage();
}
catch( err ) {
errorMessage( err );
}
document.body.removeChild( textArea );
}
function errorMessage( err ) {
alert( 'Copy to clipboard failed ' + ( err || '' ) )
};
}