Post by: Niraj Dhungana
Posted on: Nov 29, 2021
Sometimes even small things add the best user experience in our webapp. And copy to clipboard button is one of those. You can check out the demo by clicking on the button below.
Have you clicked on this button? Now paste using
ctrl+v or by right click. There is something right? Let’s see how we can create this copy-to-clipboard button.
To create this we have an object called navigator. This object contains the information about browsers. Most of the major browsers support it. You can read more about it here.
Let’s create an HTML page where we will add a simple button which can copy the text.
In this code we are simply selecting our
button with it’s id
btn and adding an click
eventListener. Now we need to create this method
copyToClipboard. Where we will write our actual logic.
Handling error and success
navigator.clipboard.writeText() returns a promise. So, we can use the
then() method to capture success and error both.
Now here if the copy process is successful then I want to change the text inside that button for two second. Otherwise if anything goes wrong I want to log that to the
Also you can display any kind of alert or notification to the user on the success or on the error.
Here you can see I am using this text "Subscribe to Full Stack Niraj". You can use any text or also user input value here to copy. Then we have a method for success.
Where we are changing the
innerHTML of the button to the
copied for two seconds and then changing back to the previous text. Also there is a method which logs errors if anything goes wrong.
Complete source code.