Copy to Clipboard Javascript Button to copy text


A modern approach to copy text to clipboard, just click on Button/Text/Input Box. You copy text to the clipboard without flash in HTML/PHP using JS(Javascript). Copy to Clipboard easy way to Make Your Website More Impressive.


Let's We have trying to make a button that can copy to clipboard the text in an input element.

JS:

<!-- pure javascript solution for Copy text to clipbord-->

function copyToClipboard(s)
{
 var input = document.getElementById("ta1");
 input.focus();
    input.select();
    document.execCommand('Copy');
}

Html:

<form name="copypasteform" id="copypasteform">

<div id="visible">
<textarea rows="10" cols="50" name="ta1" id="ta1">Some Text.</textarea>
</div>

<p>
<input type="button" value="Show/Hide" id="show" >
<input onclick="copyToClipboard(document.getElementById('ta1').value);" type="button" value="Copy" class="custombutton">

</p>

</form>

CSS:

#visible {
    display:none;

    }


Copy to clipboard – pure javascript solution Example



<!DOCTYPE html>
<html>
<HEAD>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>

<style>
#visible {
     display:none;
    }
</style>
</head>

<body>
<section>


<form name="copypasteform" id="copypasteform">
  <div id="visible">
<textarea rows="10" cols="50" name="ta1" id="ta1">Some Text.</textarea>
  </div>
<p>
   <input type="button" value="Show/Hide" id="show" >
   <input onclick="copyToClipboard(document.getElementById('ta1').value);" type="button" value="Copy" class="custombutton">
   <input onclick="document.getElementById('ta1').value='';" type="button" value="Clear" class="custombutton">
  </p>
</form>



<script type="text/javascript">

<!--Show/Hide Button JS-->

$(document).ready(function(){
    $("#show").click(function(){
        $('#visible').slideToggle();            
        
    });
})



<!--Copy to clipbord + Clear button-->

function copyToClipboard(s)
{
 var input = document.getElementById("ta1");
 input.focus();
    input.select();
    document.execCommand('Copy');

 if ( document.selection ) {
        document.selection.empty();
    } else if ( window.getSelection ) {
        window.getSelection().removeAllRanges();
    }
}
</script>


</section>

</body>
</html>



Download HTML

Comments