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

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

var copyTextareaBtn = document.querySelector('.js-textareacopybtn');
copyTextareaBtn.addEventListener('click', function(event) {
  var copyTextarea = document.querySelector('.js-copytextarea');;
  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');

Working Example:

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

Other important pages with some suggestions for blogger template coding.

Share this Article :

No comments:

Post a Comment