I'm having an issue using JS to copy text

This is a two-fold problem. I am able to add words to a textarea by clicking on links for each word and I can copy the text in that textarea using the following code:

function copy() {
  var copyText = document.getElementById("text-box");
  copyText.select();
  document.execCommand("copy");
}
document.querySelector("#copy").addEventListener("click", copy);

Where “text-box” is the id for the “textarea” and “#copy” is the id of the copy button. That works like a charm and the text is even selected, even though in VS Code I get a deprecated warning for document.execCommand.

However, I also want to be able to manually edit the textarea with punctuation, carriage returns, etc. But as soon as I manually edit the area I can no longer add words to the area by clicking the links for the words I want to add. So I lose functionality as soon as I manually edit the area.

I also have a div tag with the attribute contenteditable=“true” and I can add words to that area by clicking the words, then editing, so on, and so on. However, the copy button does not copy the text in the div area. The div does what the textarea doesn’t and vice versa.

I either need to copy the text from the div area or be able to edit the textarea and still be able to click and add words to the area. Did I explain that correctly or is it confusing? Is there a solution for both issues? Does the issue(s) have something to do with block vs inline elements?

I’m looking for a solution now using the Clipboard API because maybe Document.execCommand() is the issue.

It would be helpful if you could provide some screenshots and/or link to your current code.

Just to confirm about what the project is trying to do - there’s a textbox that the user can type into as normal, or click a button to add words to it, and then when the user is finished they can click a button to copy the text to their clipboard. Is that right?

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.