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.


Table of Contents


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>


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

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

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

document.getElementById("msg").innerHTML = "Copied";


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

#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;

Leave a Reply

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