2

how can I copy the content of the element into the clipboard when I click on an element.

<h1 class="copy"> i want to copy this text on clipboard when I click on an element.</h1>
<p> i want to copy this text on clipboard<p>

Is it possible to copy without creating any element? Is there a solution similar to this?

$(function (){
$("h1").click(function (){
   $(this).select();
   document.execCommand("copy");
});

});

How can I do this with jquery or regular javascript. Or what are your other suggestions? Thanks

heybelix
  • 35
  • 1
  • 4

2 Answers2

4

You can use the navigator clipboard API. It is supported by all modern browsers.

document.querySelector(".copy").onclick = (e) => {
  navigator.clipboard.writeText(e.currentTarget.innerText);
}
mockingjay
  • 181
  • 1
  • 10
0

html:

<h1><button class="copy"> i want to copy this text on clipboard when I click on an element.</button></h1>

jquery:

$(".copy").on('click', function (){
  var text = $(this).text()
  console.log(text)
  var $temp = $("<input>");
  $("body").append($temp);
  $temp.val(text).select();
  document.execCommand("copy");
  $temp.remove();

}); 
Liza Amatya
  • 141
  • 6