How to verify clipboard is empty in Javascript?

Viewed 357

I'm trying to copy the display result in the clipboard. Copying is working fine. But I wanted to verify if the clipboard is empty or not. I have tried to match the div is empty, but its not helping. Can anyone help?

function num_Gen() {

  document.getElementById('display100').innerHTML = document.getElementById('num1').value;

}

function CopyClip(copy_num) {
  
  var cpy = document.createRange();
  var text = document.getElementById("copy_num");
  cpy.selectNode(document.getElementById("copy_num"));
  window.getSelection().removeAllRanges();
  window.getSelection().addRange(cpy);
  document.execCommand('copy');
  window.getSelection().removeAllRanges();
  if (text === "") {
    alert("Nothing copied");
  }else{
  var bubble = document.getElementById("display_num");
  bubble.innerHTML = "   value copied";

 }
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Value Gen</title>
</head>

<body>
  <script src="scr.js"></script>


  <input type="text" name="num1" id="num1" required><br><br>

  <input type="button" id="display1" onclick="num_Gen()" value="View Number" />


  <button type="button" id="copy" onclick="CopyClip()">copy</button>
  <span class="bubbletext" id="display_num"></span>
  <p></p>
  <div id="copy_num">
    <span id='display100'></span><br>
  </div>
</body>
</html>

1 Answers

As per i understood your question you can try this

function num_Gen() {
  document.getElementById('display100').innerHTML = document.getElementById('num1').value;
}

function CopyClip(copy_num) {
  
  var cpy = document.createRange();
  var text = document.getElementById("copy_num");
//Checking for empty value before perform copy 
//getting div's text content and removed extra spaces
  if (text.textContent.trim() === "") {
    alert("Nothing copied");
    //nothing copied return 
    return;
  }
  cpy.selectNode(document.getElementById("copy_num"));
  window.getSelection().removeAllRanges();
  window.getSelection().addRange(cpy);
  document.execCommand('copy');
  window.getSelection().removeAllRanges();

  var bubble = document.getElementById("display_num");
  bubble.innerHTML = "   value copied";
}
 <input type="text" name="num1" id="num1" required><br><br>
  <input type="button" id="display1" onclick="num_Gen()" value="View Number" />


  <button type="button" id="copy" onclick="CopyClip()">copy</button>
  <span class="bubbletext" id="display_num"></span>
  <p></p>
  <div id="copy_num">
    <span id='display100'></span><br>
  </div>

Related