0

I'm trying to write JS code that can copy the content of a td and, at the same time, shows some kind of notification to let the user know that something has been copied to the clipboard. I tried the following code and the copying to clipboard works fine, but the notification never worked. What should I do?

PHP and HTML:

echo "<td onClick='copy(this),selectThis(this)'> " . $row['email'] . "</td>";

JS:

<script type="text/javascript">
    function copy(that){
        var inp =document.createElement('input');
        document.body.appendChild(inp)
        inp.value =that.textContent
        inp.select();
        document.execCommand('copy',false);
        inp.remove();
    }
    function selectThis(element) {
        document.createElement("input")).style.backgroundColor = "red";
    }
</script>
Daniel_Knights
  • 7,940
  • 4
  • 21
  • 49
Deller
  • 29
  • 7
  • 1
    Does this answer your question? [How do I copy to the clipboard in JavaScript?](https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript) – Tân Aug 13 '20 at 03:54
  • Thanks for your comment sir, but I don't want the alert box, very ugly and wasting time. i need something like message fade in and out, or something at the right bottom of the cell – Deller Aug 13 '20 at 03:57
  • *i need something like message fade in and out, or something at the right bottom of the cell* I think you need https://codeseven.github.io/toastr/demo.html – abhay Aug 13 '20 at 07:43

1 Answers1

1

'use strict';
function copy(that){
 // ...
 notify(that.textContent);
}

function notify(content) {
  let notification = document.createElement('span');
  notification.classList.add('notification');
  notification.textContent = `"${content}" copied`;
  document.body.prepend(notification);
  setTimeout(() => notification.remove(), 4000);
}
.notification {
  border: solid 1px green;
  padding: 5px;
  animation-name: fade;
  animation-duration: 4s;
  animation-iteration-count: 2;
  animation-direction: alternate;
 }
 
@keyframes fade {
  from { opacity:0; }
  to { opacity:1; }
}
<p onclick="copy(this)" id="element" >Click here to copy this text (figuratively).</p>
Chiara Ani
  • 918
  • 7
  • 25