Copy to clipboard function with example

 > Tech >  Copy to clipboard function with example
0 Comments
Copy to clipboard

This is my second post in a row related to problem-solving (helping other engineers). If you want to see my last post, you can visit https://lnkd.in/dheqUD7E

So I pick another small problem with a large impact, which is copying text from any input field.

Many of us use third-party packages or plugins like clipboard.js or copy-to-clipboard only to copy values from input elements. These packages/plugins provide vast features and capabilities but at the cost of large bundle sizes.

To solve this problem, why not use this simple helping method and reduce the effort and cost of those packages/plugins?

<input type="text" value="It is our duty to be better today than we were yesterday, and better tomorrow than we are today" id="quote">

<button onclick="copyToClipboard(quote)">Copy Quote</button>

<script>
const copyToClipboard = (quote) => {
 let value = quote.value;
 let clipboard = navigator.clipboard;
 let result = clipboard.writeText(value);
 result ? result : Promise.reject('Sorry!!, but clipboard API is not available.'); 
};
</script>