Async Copy API 2018 with setTimeout and fetch

Demo for the new asynchronous clipboard api

by dan8

HTML

<a href="https://w3c.github.io/clipboard-apis/#async-clipboard-api">
  <h3>Asynchronous Clipboard API with setTimeout and fetch</h3>
</a>

<button id="copyme">
  Copy Me!
</button>
<br/>
<div id="result"></div>
<br/><hr/><br/>
Try to paste 😉 <br/>
<textarea rows="4" cols="40"></textarea>

CSS

#result {
  font-weight: bold;
  margin: 12px 0;
  height: 20px;
}

JavaScript 1.7

const copy = document.getElementById('copyme');
copy.addEventListener('click', copyPageUrl);

function copyPageUrl() {
		setTimeout(() => {
      fetch('https://jsonplaceholder.typicode.com/posts/1')
        .then(response => response.json())
        .then(async (json) => {
          try {
            await navigator.clipboard.writeText(json.title);
            document.getElementById('result').innerHTML = 'Copied!';
            console.log('Copied to clipboard');
          } catch (err) {
            document.getElementById('result').innerHTML = 'Could not copy!';
            console.error('Failed to copy: ', err);
          }    
          setTimeout(() => {
            document.getElementById('result').innerHTML = '';
          }, 3000);
        });
  	}, 2000);
};