copy email click button in javascript

To copy an email address to the clipboard when a button is clicked in JavaScript, you can use the following code:

index.tsx
function copyEmail() { 
  var email = "example@example.com"; // replace with the desired email address
  
  var tempInput = document.createElement("input");
  tempInput.value = email;
  document.body.appendChild(tempInput);
  
  tempInput.select();
  document.execCommand("copy");
  document.body.removeChild(tempInput);
}

// Example button element
var copyButton = document.getElementById("copyButton"); // replace "copyButton" with the id of your button element
copyButton.addEventListener("click", copyEmail);
514 chars
16 lines

This code creates a temporary input element, sets its value to the email address, appends it to the document body, selects its contents, and executes the copy command. Finally, it removes the temporary input element from the document body.

Make sure to replace "example@example.com" with the actual email address you want to copy, and replace "copyButton" with the id attribute of your button element.

Note: Due to browser security restrictions, the copy command may not work if it is not triggered by a user action, such as a button click.

related categories

gistlibby LogSnag