0

I was tried to copy paragraph content when I click on it, I wrote this code but it's not working correctly

here the code:

$('p').click(function (e) {
    e.preventDefault();
    var $temp = $("<input>");
    $temp.val($(this).html()).select();
    document.execCommand("copy");
    $temp.remove();
});
MoHamed HaSsn
  • 555
  • 1
  • 6
  • 20

1 Answers1

1

Here, this adds a click listener and filters on P tags. When clicked it will copy to clipboard.

const copyElement = (e) => {
  let selection = window.getSelection();
  if (selection.rangeCount > 0) {
    selection.removeAllRanges();
  }
  
  let range = document.createRange();
  range.selectNode(e);
  selection.addRange(range);
  document.execCommand('copy');
};

document.addEventListener('click', (e) => {
  if(e.target.matches('p')) {
    copyElement(e.target);
  }
});
<p>Testing</p>
<div>No copy</div>
<p>Test2</p>
Bibberty
  • 4,670
  • 2
  • 8
  • 23
  • i love it works great... I am trying to add a copy image on click.... i replaced 'p' with 'img' in 2nd to last line and it select the image with an outline but my clipboard doesnt copy the image, its just blank... any tweaks you can add for images as well? – jon rios Apr 13 '20 at 21:14