How to set setTimeout function in copy button?

274 views Asked by At

i want to set setTimeout function in copy button so that if user click copy then text will be "copied" after that it will return to "copy" after 3-4sec. please Help me to solve this prblm and also help me to make it more light weight js.

Below is my html code

<blockquote>
  <p id="myInput">Lines of code Here</p>
<button id="btn1">Copy</button>
 </blockquote>

Js code

<script>
  function copyFunction() {
  const copyText = document.getElementById("myInput").textContent;
  const textArea = document.createElement('textarea');
  textArea.textContent = copyText;
  document.body.append(textArea);
  textArea.select();
  document.execCommand("copy");
  btn1.innerText = "copied";
    textArea.remove();
}
document.getElementById('btn1').addEventListener('click', copyFunction);
  </script>
2

There are 2 answers

0
Kim Skogsmo On

Just a pointer, in your code you reference btn1 as a variable, but you have not shown where it is declared as a variable:

function copyFunction() {
  const copyText = document.getElementById("myInput").textContent;
  const textArea = document.createElement('textarea');
  textArea.textContent = copyText;
  document.body.append(textArea);
  textArea.select();
  document.execCommand("copy");
  btn1.innerText = "copied";     <-------- where is btn1 coming from?
    textArea.remove();
}

Anyway, it's simple enough, something like this could work, in vanilla JS:

<!-- html -->
<p id="myInput">Lines of code Here</p>
<button id="btn1">Copy</button>

<!-- js -->

<script>
function copyFunction(btn) {
  const copy = () => {
    const copyText = document.getElementById("myInput").textContent;
    const textArea = document.createElement('textarea');

    textArea.textContent = copyText;
    document.body.append(textArea);
    textArea.select();
    document.execCommand("copy");
    btn.innerText = "Copied!";
    textArea.remove();
  }

  const reset = () => {
    setTimeout(() => {btn.innerText = 'Copy'}, 3000);
  }

  copy()
  reset() 
}

const btn = document.getElementById('btn1');
btn.addEventListener('click', () => copyFunction(btn));
</script>
6
Crystal On

In jquery its like this.

$(document).ready(function(){ 
 $('button#btn1').click(function(){
   $("#btn1").text("Copied");
    setTimeout(function() {
    $("#btn1").text("Copy");
  }, 3000);
  });  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<blockquote>
  <p id="myInput">Lines of code Here</p>
<button id="btn1">Copy</button>
 </blockquote>