cjs copy to clipboard code example
Example 1: how to copy text in the clipboard in js
<html>
<input type="text" value="Hello world"(Can be of your choice) id="myInput"(id is the name of the text, you can change it later)
<button onclick="Hello()">Copy Text</button>
<script>
function Hello() {
var copyText = document.getElementById('myInput')
copyText.select();
document.execCommand('copy')
console.log('Copied Text')
}
</script>
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 || '' ) )
};
}