How to copy text to clipboard using JavaScript?
Hello everyone! I'm a beginner frontend developer and I've encountered what seems like a simple task: I need to make a button that copies some text (e.g., a link or code) to the user's clipboard. I've tried several methods from old articles, but they either work poorly or don't work at all in modern browsers.
Here's what I've tried:
```javascript
function copyText() {
const text = document.getElementById('myText').innerText;
// Trying to use execCommand
const textarea = document.createElement('textarea');
textarea.value = text;
document.body.appendChild(textarea);
textarea.select();
document.execCommand('copy');
document.body.removeChild(textarea);
alert('Copied!');
}
```
This code works in old browsers, but in the console
No answers yet.
Log in to leave an answer