When pressed, the button changes the text and returns back after a while

Viewed 36

There are several buttons on the page that, when clicked, copy the text to the clipboard. I don't know how to change the text of the button after it is clicked so that the text then returns to its original state. For example: Battle.net changes to !Copied! and after 3 seconds returns back to Battle.net

I am a beginner, I will be glad to a detailed explanation.

HTML:

<p id="battlenet-id">GameID#1234</p>
<p id="xbox-id">GameID#5678</p>
<li><a href="javascript:void(0);" class="link-battlenet" onclick="copy('battlenet-id')" ><i class="fab fa-battle-net"></i> Battle.net</a></li>
<li><a href="javascript:void(0);" class="link-xbox" onclick="copy('xbox-id')" ><i class="fa-brands fa-xbox"></i> Xbox</a></li>

JS:

function copy(element_id) {
  var aux = document.createElement("div");
  aux.setAttribute("contentEditable", true);
  aux.innerHTML = document.getElementById(element_id).innerHTML;
  aux.setAttribute("onfocus", "document.execCommand('selectAll',false,null)");
  document.body.appendChild(aux);
  aux.focus();
  document.execCommand("copy");
  console.log(" Copied to clipboard!");
  document.body.removeChild(aux);
}
1 Answers

Passing this as a parameter to the copy() function allows you to access the clicked button properties, in this case textContent.

function copy(element_id, thisButton) {

  // SAVE BUTTON's TEXT
  let oldText = thisButton.textContent
  
  // SET BUTTON'S NEW TEXT
  thisButton.textContent = '!copied!'
  
  // AFTER 3 SECONDS, SET THE BUTTON'S TEXT BACK
  const timeout = setTimeout(function() { thisButton.textContent = oldText }, 3000);
  
  
  
  var aux = document.createElement("div");
  aux.setAttribute("contentEditable", true);
  aux.innerHTML = document.getElementById(element_id).innerHTML;
  aux.setAttribute("onfocus", "document.execCommand('selectAll',false,null)");
  document.body.appendChild(aux);
  aux.focus();
  document.execCommand("copy");
  console.log(" Copied to clipboard!");
  document.body.removeChild(aux);
}
<p id="battlenet-id">GameID#1234</p>
<p id="xbox-id">GameID#5678</p>
<li><a href="javascript:void(0);" class="link-battlenet" onclick="copy('battlenet-id', this)"><i class="fab fa-battle-net"></i> Battle.net</a></li>
<li><a href="javascript:void(0);" class="link-xbox" onclick="copy('xbox-id', this);"><i class="fa-brands fa-xbox"></i> Xbox</a></li>

Related