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

You must be visiting this page because you want to know a method to add a COPY button under some text in your website. Once i needed it too and discovered the following code. Its not written by by but it works perfectly.


How this code works :

Before we proceed you have to understand some basics of this code. 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 whereever he/she wants.

(If you want to do something else then I M Sorry !!!)

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

Working Example:




This script works perfectly for me in most of the browsers.

Other important pages with some suggestions for blogger template coding.

No comments:

Post a Comment