How to Copy Text to Clipboard using JavaScript

AuthorSumit Dey Sarkar

Pubish Date11 Sep 2022

categoryJavaScript

In this tutorial we will learn how to copy text to clipboard using javaScript.

Let's see a example -

How to Copy Text to Clipboard using JavaScript

<!DOCTYPE html>
<html>
<head>
	<title>How to Copy Text to Clipboard using javaScript</title>
	<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
	<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/1.5.16/clipboard.min.js"></script>
</head>
<body>

<div class="container mt-5">
    <h3>How To Copy Text To Clipboard Using javaScript</h3>
    <textarea id="copyArea" class="form-control" placeholder="Write Something for Copy"></textarea>
<button class="btn copyBtn bg-success text-white mt-2" data-clipboard-action="cut" data-clipboard-target="#copyArea">Copy Text</button>
</div>

<script type="text/javascript">
	var clipboard = new Clipboard('.copyBtn');


	clipboard.on('success', function(e) {
	    e.clearSelection();
	    alert('Copy text to Clipboard Successfully');
	});

	clipboard.on('error', function(e) {
	    alert('Not Copied!');
	});
</script>


</body>
</html>

 

Output

jQuery

Comments 0

Leave a comment