Copy TEXT to Clipboard on Button Click

Copy to clipboard is a very common task and we use it often in computer, laptop and mobile.

This tutorial will explain about how to copy text to clipboard on button click using JavaScript.

Contents
HTML
JavaScript
CSS

Table of Contents

HTML

Create markup with input box having a text in value and a button calling function on click.

<input type="text" name="mytext" id="mytext"  value="Phpcluster Programming Blog"> 
<button name="copy" id="copybtn" onclick="copyText()">Copy Text</button> <span id="msg"></span>

JavaScript

Firstly we select text field,then use execCommand() to copy Text to clipboard.

<script>
function copyText()
{
var mytext = document.getElementById("mytext");	
	
mytext.select(); //select text field

document.execCommand("copy");  //Copy text

document.getElementById("msg").innerHTML = "Copied";
}	
</script>

CSS

Style is used to set layout of input field and button.

<style>
#mytext {
    outline: none;
    background: none;
    width: 25%;
    padding: 10px 10px;
    border: 1px solid #eeeee;
    font-size: 1em;
    font-weight: 100;
    margin-bottom: 1em;
}
#copybtn {
    background: #33b7ff;
    border: 0;
    border-bottom: 3px solid rgba(73,134,18,.3);
    padding: 10px 10px;
    color: #fff;
    font-weight: 400;
    font-size: 20px;
    transition: border-color 1s;
    text-decoration: none;
    white-space: nowrap;
}
</style> 

Leave a Reply

Your email address will not be published. Required fields are marked *