Copy2 button

Since I found a good code for copying, I made a page at http://dot.kr/Q/copyButton/31.php .
If I click the button “copy”, it copies “Hello World”.
It works fine.

Now I like to add another button “copy2” to the page for copying “Hello World2”.
Can I do it with your help?

You can give each button a class, so that you can attach an event handler to each.

You can also store the text to be copied (for example) in a data attribute.

Something like this:

<button class="copy" data-copy="Hello World!">COPY</button>
<button class="copy" data-copy="Hello, 2nd World!">COPY2</button>

and:

function copyToClipboard(val) {
  const t = document.createElement("textarea");
  document.body.appendChild(t);
  t.value = val;
  t.select();
  document.execCommand('copy');
  document.body.removeChild(t);
}

const copyButtons = document.querySelectorAll('.copy');

copyButtons.forEach((button) => {
  button.addEventListener('click', function() {
    copyToClipboard(this.dataset.copy);
    console.log('Copied!');
  });
});
2 Likes