r/JavaScriptTips • • Jan 19 '23

How to copy text to clipboard with async/await result-handling

Post image
12 Upvotes

2 comments sorted by

1

u/Low_Mammoth_9371 Jan 19 '23

Code to copy:

<input type="text" id="input">
<button onclick="copyToClipboard()">Copy to clipboard</button>
<div id=output></div>

<script>

async function copyToClipboard(myText) {
    try {
        let input;
        input = document.getElementById('input').value;
        await navigator.clipboard.writeText(input);
        alert("Copy successful!")
    } catch {
        alert("Copy failed! "+ err);
    }
}

</script>