To copy text to the clipboard in JavaScript, you can use the execCommand
method of the document
object, along with the copy
command. The execCommand
method allows you to execute a command on the current document, such as copying text to the clipboard or printing the document.
Here is an example of how to use the execCommand
method to copy text to the clipboard:
function copyToClipboard(text) {
// Create a textarea element
let textarea = document.createElement('textarea');
// Set the text and style of the textarea
textarea.textContent = text;
textarea.style.position = 'fixed'; // Prevent scrolling to bottom of page in MS Edge.
document.body.appendChild(textarea);
// Select the textarea
textarea.select();
// Copy the text to the clipboard
document.execCommand('copy');
// Remove the textarea
document.body.removeChild(textarea);
}
To use this function, you can call it with the text that you want to copy to the clipboard as an argument. For example:
copyToClipboard('Hello, world!');
This will copy the text “Hello, world!” to the clipboard, and the user can paste it into another application or document.
Note that the execCommand
method has some limitations and may not work in all browsers or environments. It is also