Copy to clipboard using javascript
HTML5 browser API is amazing which empowers you to do lots of things without any third-party libraries. One of them is clipboard copy with simple JS code.
you just need to call the navigator and then call the writeText clipboard method. It’s an async function and you need to use a promise to handle the success or error returned.
Copy to clipboard
The HTML code could be like this:
<p id="text">This is a sample text to copy to clipboard</p>
<button id="copyBtn">copy to clipboard!</button>
and then in your JS code we first define the elements:
const text = document.getElementById("text")const copyBtn = document.getElementById("copyBtn")
and then handle the the event listener like this:
copyBtn.addEventListener("click", () => { navigator.clipboard.writeText(text.innerText) .then(() => copyBtn.innerText = 'text copied!') .catch(err => console.log(err))})
it works like a charm! you can check your clipboard by pasting it anywhere you want.
Paste from clipboard
Also navigator support Pasting function. Imagine we have another button for paste from clipboard:
<button id="pasteBtn">paste from clipboard!</button>
and then in your JS code:
pasteBtn.addEventListener("click", () => { navigator.clipboard.readText() .then((result) => alert(result)) .catch(err => console.log(err))})
here we just alert the result. you can append it in any element you want.
enjoy it ;)