1

I'm trying to add a small popup tooltip to the following code to show that text was successfully copied to the clipboard when the element is clicked. I would like the tooltip to popup saying "Copied" on a click or touch in the case of mobiles for a second, then disappear untill another item is copied.

The code is as follows:

const tds = document.querySelectorAll("td");

tds.forEach(td => {
  td.onclick = function() {
    document.execCommand("copy");
  }

  td.addEventListener("copy", function(event) {
    event.preventDefault();
    if (event.clipboardData) {
      event.clipboardData.setData("text/plain", td.textContent);
      console.log(event.clipboardData.getData("text"))
    }
  });
})
<table><tbody><tr><td>Data 1</td><td>Data 2</td><td>Data 3</td></tr></tbody></table>
Ads
  • 47
  • 7

1 Answers1

0

Here is an solution without using jQuery (I assume you dont use it since its not present in the code you showed us):

const tds = document.querySelectorAll("td");

tds.forEach(td => {
  td.onclick = function() {
    document.execCommand("copy");
    // ------- code added from here -------
    this.className = 'copied';
    var td = this;
    setTimeout(function() {
       td.className = '';
    }, 1000)
    // -------      up to here      -------
  }

  td.addEventListener("copy", function(event) {
    event.preventDefault();
    if (event.clipboardData) {
      event.clipboardData.setData("text/plain", td.textContent);
      console.log(event.clipboardData.getData("text"))
    }
  });
})
td.copied:after {
content: "copied";
background-color: red;
padding: 5px;
display: block;
position: absolute;
}
<table><tbody><tr><td>Data 1</td><td>Data 2</td><td>Data 3</td></tr></tbody></table>

When clicking on a td then for one second the copied class is added which has an :after pseudo-element that acts as your desired popup

Kristianmitk
  • 4,528
  • 5
  • 26
  • 46