JSFiddle - React, Tailwind, and code Playground

HTML5 copy + jQuery fn

by tonytlwu

HTML

<p>Email me at <a class="js-emaillink" href="mailto:[email protected]">[email protected]</a></p>

<p><button class="js-emailcopybtn">Copy</button></p>

JavaScript

HTMLElement.prototype.copyText = function() {
  var range = document.createRange();  
  range.selectNode(this);  
  window.getSelection().addRange(range);

  try {  
    // Now that we've selected the anchor text, execute the copy command  
    var successful = document.execCommand('copy');  
    var msg = successful ? 'successful' : 'unsuccessful';  
    console.log('Copy was ' + msg);
  } catch(err) {  
    console.log('Oops, unable to copy');  
  }

  // Remove the selections - NOTE: Should use
  // removeRange(range) when it is supported  
  window.getSelection().removeAllRanges();
};

if (typeof jQuery !== 'undefined') {
	$.fn.copyText = function(){
  	return $(this).each(function(i){
    	if (i > 0) return;
      console.log('Copying using jQuery');
      this.copyText();
    });
  }
}

var copyEmailBtn = document.querySelector('.js-emailcopybtn');  
copyEmailBtn.addEventListener('click', function(){
	var selector = '.js-emaillink';
  // Select the email link anchor text  
  // document.querySelector(selector).copyText();
  $(selector).copyText();
}, false);