简体   繁体   中英

copy text onclick from <p> tag

                          <div class="d-flex flex-row justify-content-between">
                            <p class="mb-0 me-1 py-2 ps-4 add-text" id="p1">ygwbfewilskfhnewisfklnewiofjfhjky</p>
                            <button class="btn-primary w-20 px-3 copy-btn" onclick="copyToClipboard('#p1')">Copy<i class="fa-regular fa-copy ps-2"></i></button>
                          </div>

JS:

    function copyToClipboard(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(element).text()).select();
document.execCommand("copy");
$temp.remove();
}

I want to copy the text in the p id="p1".

I tried this method because I saw it work for someone else but it doesn't work for me

Your code is good and there is nothing wrong with it. I think that you might have forgotten to add jQuery to it. You can do this by adding the following code in your <head> tag of your HTML code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

Your code works completely fine, you can view it here If it still doesn't work, you probably have JavaScript blocked. Check to make sure you don't have an extension blocking JS and check your browser settings as well to make sure JS is allowed.

(I am required to have the code as it is a codepen link)

<div class="d-flex flex-row justify-content-between">
  <p class="mb-0 me-1 py-2 ps-4 add-text" id="p1">ygwbfewilskfhnewisfklnewiofjfhjky</p>
  <button class="btn-primary w-20 px-3 copy-btn" onclick="copyToClipboard('#p1')">Copy<i class="fa-regular fa-copy ps-2"></i></button>
</div>

function copyToClipboard(element) {
  var $temp = $("<input>");
  $("body").append($temp);
  $temp.val($(element).text()).select();
  document.execCommand("copy");
  $temp.remove();
}

Here is a vanilla version of doing this so. If you read the blog post in my comment on the OP question, the jQuery method relies on Adobe Flash and is not fully supported across all browsers.

 function copyToClipboard() { var range = document.createRange(); range.selectNode(document.getElementById("p1")); window.getSelection().removeAllRanges(); // clear current selection window.getSelection().addRange(range); // to select text document.execCommand("copy"); window.getSelection().removeAllRanges();// to deselect }
 <div class="d-flex flex-row justify-content-between"> <p class="mb-0 me-1 py-2 ps-4 add-text" id="p1">ygwbfewilskfhnewisfklnewiofjfhjky</p> <button class="btn-primary w-20 px-3 copy-btn" onclick="copyToClipboard('#p1')">Copy<i class="fa-regular fa-copy ps-2"></i></button> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM