Copy Text to Clipboard | Javascript

 function copyToClipboard() {

  const copyText = document.getElementById("myInput");
  copyText.select();
  document.execCommand("copy");
  
}
//new API
function copyToClipboard(){
 navigator.clipboard.writeText(document.querySelector('#myInput').value)
} 

AI Explanation

This code snippet shows two different ways to copy text to the clipboard using JavaScript. The first function `copyToClipboard()` uses the older method for copying text to the clipboard. It first selects the text inside an input element with the id "myInput" using `copyText.select()`, and then executes the `document.execCommand("copy")` method to copy the selected text to the clipboard. The second function `copyToClipboard()` uses the newer Clipboard API method `navigator.clipboard.writeText()` to copy text to the clipboard. It fetches the value of the input element with the id "myInput" using `document.querySelector('#myInput').value` and then calls `navigator.clipboard.writeText()` with the text content to copy to the clipboard. It is important to note that these two functions have the same name `copyToClipboard()`, which can potentially lead to conflicts or unexpected behavior in the code if both are present in the same script. The correct approach would be to rename one of the functions to avoid naming conflicts.