How to add a Copy Button under some text on your website

How to add a Copy Button under some text on your website

 

 You are here because you want to know a method to add a COPY button under some text in your website. here i have written some code that works perfectly.

How this code works :

Before we proceed you have to know some basics concept of the javascript and Html. At first we need a textarea where we put the text to be copied. Then there is a "COPY IT" Button just after the textarea. When the user clicks on "COPY IT" button, the text in textarea is copied to clipboard. Then the user can paste that text any where you want. 

 



   <p>
  <textarea class="js-copytextarea">
  Sample Text to be copied</textarea><br />
</p>
<p>
  <button class="js-textareacopybtn">Copy it</button>
</p>



<script> var copyTextareaBtn = document.querySelector('.js-textareacopybtn'); copyTextareaBtn.addEventListener('click', function(event) { var copyTextarea = document.querySelector('.js-copytextarea'); copyTextarea.select(); try { var successful = document.execCommand('copy'); var msg = successful ? 'successful' : 'unsuccessful'; console.log('Copying text command was ' + msg); } catch (err) { console.log('Oops, unable to copy'); } }); </script>


example-


Post a Comment

0 Comments