js copy to clipboard cross browser

Solutions on MaxInterview for js copy to clipboard cross browser by the best coders in the world

showing results for - "js copy to clipboard cross browser"
Bjorn
27 Apr 2016
1<script>
2function copyToClipboard(element) {
3  var $temp = $("<input>");
4  $("body").append($temp);
5  $temp.val($(element).text()).select();
6  document.execCommand("copy");
7  $temp.remove();
8}
9</script>
10
11<p id="text">Hello</p>
12<button onclick="copyToClipboard('#text')"></button>
Anna
26 Jan 2019
1/** copy text to the clipboard */
2function copy2clipboard( text, callback /* optional */ ) {
3
4	// use modern clipboard API
5	if ( navigator.clipboard ) {
6		navigator.clipboard.writeText( text )
7		.then( function(){
8			// if a callback is provided, call it
9			callback && callback();
10		}).catch( function( err ){
11			errorMessage( err );
12		}); 
13	}
14	// use old document.execCommand('copy')
15	else {
16
17		// create a temporary textArea containing the text
18		var textArea = document.createElement( 'textarea' );
19		textArea.setAttribute( 'style', 'width:1px;border:0;opacity:0;' );
20		document.body.appendChild( textArea );
21		textArea.value = text;
22
23		// select the textArea
24		textArea.select();
25
26		try {
27
28			// copy from textArea
29			var isCopied = document.execCommand('copy');
30
31			// if copy was successful, and a callback is provided, call it. if copy failed, display error message
32			isCopied ? ( callback && callback() ) : errorMessage();
33
34		} 
35		catch( err ) {
36			errorMessage( err );
37		}
38		// remove temporary textArea
39		document.body.removeChild( textArea );
40	}
41
42	/** display error message */
43	function errorMessage( err ) { 
44		alert( 'Copy to clipboard failed ' + ( err || '' ) ) 
45	};
46    
47}
similar questions
queries leading to this page
js copy to clipboard cross browser