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
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
Share Improve this question edited Jun 2, 2021 at 11:31 heybelix asked Jun 2, 2021 at 11:23 heybelixheybelix 571 silver badge4 bronze badges 2- stackoverflow./questions/36639681/… – Muhammad Asif Commented Jun 2, 2021 at 11:25
- Does this solve your issue? 30secondsofcode/blog/s/… – ciekals11 Commented Jun 2, 2021 at 11:25
2 Answers
Reset to default 4You can use the navigator clipboard API. It is supported by all modern browsers.
document.querySelector(".copy").onclick = (e) => {
navigator.clipboard.writeText(e.currentTarget.innerText);
}
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();
});