How to Make a Copy to Clipboard Button using JavaScript?

To make a copy to clipboard button, you can use the document.execCommand() method. The execCommand() method is used to execute the clipboard commands such as cut, copy and paste.

Let’s say we have a text input in our HTML document and we want to copy its text whenever we click on the copy to clipboard button:

<input type="text" id="target" placeholder="Type something..." >
<button onclick="copyText()">Copy to clipboard</button>

The copyText() function will be invoked every time we click on the copy to clipboard button and copy the value of the text input.

You can paste this copied value anywhere using the ctrl+v command:

Example:

function copyText(){
    const target = document.getElementById('target');
    target.select();
    target.setSelectionRange(0, 99999); /* For mobile devices */
    document.execCommand('copy');
    alert('Text copied');
}

Method 2: Using the Clipboard API

The document.execCommand() method is now deprecated. Therefore, you should avoid it and use the writeText() method of the clipboard API instead.

See the below implementation of the copy to clipboard button:

Example:

function copyText(){
    const target = document.getElementById('target');
    target.select();
    target.setSelectionRange(0, 99999); /* For mobile devices */
    navigator.clipboard.writeText(target.value);
    alert('Text copied');
}

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.