JavaScript Clipboard Copy Function
In this article, we explored a code snippet that demonstrates how to copy text to the clipboard using JavaScript. The code snippet utilizes both the Clipboard API and the execCommand method to ensure compatibility across different browsers. By using the provided module, you can easily integrate copy functionality into your web applications.
The module also includes a showNotification
method, which displays a temporary notification on the screen to indicate whether the copy operation was successful or not.
The clipboard copy function is a useful feature that allows users to quickly copy text to their clipboard with a single click. This can really make the user experience better, especially when working with code snippets, links, or any text that users might want to use again.
How It Works
We use the navigator.clipboard.writeText()
method and the execCommand
function to copy text.
Key Concepts
-
Clipboard API: The Clipboard API is a modern JavaScript API that allows developers to interact with the clipboard. It provides a simple and secure way to read from and write to the clipboard.
-
document.execCommand method: The
execCommand
method is an older method that was widely used before the Clipboard API was introduced. It allows executing commands on the document, including copying text to the clipboard. copy-notification: This is a CSS class used to style the notification message that appears when text is copied to the clipboard.
Demo Copy to Clipboard
This section demonstrates how to copy text to the clipboard using JavaScript. Type or modify the text in the input field, then click the "Copy Text" button to copy it to your clipboard.
Try it out with this sample text:
When the button is clicked, the text "This text will be copied to the clipboard" will be copied to the user's clipboard.
JavaScript Code Main Function
The module contains two private methods: copyUsingClipboardAPI()
and copyUsingExecCommand()
. The copyUsingClipboardAPI()
method attempts to use the Clipboard API to copy the text to the clipboard. If the Clipboard API is not supported or fails, it falls back to the copyUsingExecCommand()
method, which uses the execCommand method.
The module also includes a showNotification()
method, which displays a temporary notification on the screen to indicate whether the copy operation was successful or not.
const createClipboard = () => {
// Private methods
const copyUsingClipboardAPI = async (text) => {
try {
await navigator.clipboard.writeText(text);
return { success: true, method: "Clipboard API" };
} catch (err) {
// Fallback to execCommand if Clipboard API fails
return copyUsingExecCommand(text);
}
};
const copyUsingExecCommand = (text) => {
const tempTextArea = document.createElement("textarea");
tempTextArea.value = text;
document.body.appendChild(tempTextArea);
try {
tempTextArea.select();
const success = document.execCommand("copy");
return { success, method: "execCommand" };
} catch (err) {
console.error("execCommand failed:", err);
return { success: false, method: "execCommand" };
} finally {
document.body.removeChild(tempTextArea);
}
};
// Displays a temporary notification on the screen.
const showNotification = (success, timeoutMs = 3000) => {
const message = success ? 'Text copied to clipboard!' : 'Failed to copy text to clipboard.';
const type = success ? 'success' : 'error';
const notification = document.createElement('div');
notification.textContent = message;
notification.className = `copy-notification ${type}`;
const notificationId = `copy-notification-${Date.now()}`;
notification.id = notificationId;
document.body.appendChild(notification);
setTimeout(() => {
const notifElement = document.getElementById(notificationId);
if (notifElement) {
notifElement.remove();
}
}, timeoutMs);
};
// Public methods
return {
/**
* Copies the provided text to the clipboard.
* @param {string|Object} text - The text to be copied. If an object is provided, it will be stringified.
* @param {Object} [options] - Optional settings for the copy operation.
* {
* showNotification: false - {boolean} Whether to show a notification after the copy operation.
* notificationTimeout: 3000 - {number} Timeout in milliseconds for the notification to disappear.
* callback: () => {} - {Function} Callback function to be called with the result of the copy operation.
* }
* @returns {Object} - An object containing the success status and the method used for copying.
*/
copy: async (text, options = {}) => {
// Set default values for options
const showNotificationOption = options.showNotification !== false;
const notificationTimeoutMs = options.notificationTimeout || 3000;
const callback = options.callback;
// Convert to string if the input is an object
const textToCopy = typeof text === "object" ? JSON.stringify(text) : String(text);
const result = await copyUsingClipboardAPI(textToCopy);
// Handle notification
if (showNotificationOption) {
showNotification(result.success, notificationTimeoutMs);
}
// Handle callback
if (typeof callback === 'function') {
callback(result.success, result.method);
}
return result;
}
};
};
Download Code
You can Download this JavaScript code including Minified function code
How to Use
Here is an example of how to use the createClipboard
module to copy text to the clipboard.
// Create a clipboard instance
const Clipboard = createClipboard();
Clipboard.copy("Hello, World!");
// Copy an object as JSON to the clipboard
const data = { name: "khan", age: 30 };
clipboard.copy(data);
The copy
method takes two parameters: text and options. The text parameter represents the text to be copied, and the options parameter allows for additional settings. callback and show notification
Advanced Examples
Example with call back function
// Usage examples with callback function
const Clipboard = createClipboard();
const yourText = "Hello, World!";
Clipboard.copy(yourText, {
showNotification: true, // default true
notificationTimeout: 5000,
callback: (success, method) => {
if (success) {
console.log("Copy succeeded");
// your code here
} else {
console.log("Copy failed");
}
console.log("Copy method used:", method);
}
});
In the example above, we create an instance of the createClipboard()
module and call the copy()
method, passing the text to be copied as the first argument. We also provide an options object with a callback function. The callback function is called with two arguments: success (a boolean indicating whether the copy operation was successful) and method (a string indicating the method used for copying: "Clipboard API" or "execCommand").
HTML CSS and javaScript Code Preview Live Test
You can live test this code click the button "Edit code" edit and preview real time
<div class="container">
<h1>Clipboard Copy Demo</h1>
<p>Try it out with this sample text</p>
<textarea id="copy-text" placeholder="Type some text here...">This text will be copied to your clipboard!</textarea>
<button id="copy-buuton">Copy Text</button>
</div>
<div class="container">
<h1>Copy Text Content</h1>
<p>Copy code tag text content</p>
<pre id="copy-code-text"><code>const Clipboard = createClipboard();
Clipboard.copy("Hello, World!", {
showNotification: false
}
});</code></pre>
<button id="copy-code-button">Copy Code</button>
</div>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
background-color: #f4f4f4;
}
.container {
max-width: 600px;
margin: 0 auto;
padding: 20px;
background-color: #fff;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
border-radius: 8px;
border: solid 1px #aaaa;
margin-bottom: 50px;
}
h1 {
text-align: center;
color: #333;
}
textarea {
width: 100%;
height: 100px;
margin-bottom: 20px;
padding: 10px;
border-radius: 4px;
border: 1px solid #ccc;
box-sizing: border-box;
}
pre {
background-color: #dfdfdf;
display: inline-block;
line-height: 1.5;
padding: 10px;
box-sizing: border-box;
width: 100%;
overflow: auto;
}
button {
display: block;
width: 100%;
padding: 10px;
background-color: #007BFF;
color: #fff;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
}
button:hover {
background-color: #0056b3;
}
.copy-notification {
position: fixed;
bottom: 20px;
right: 20px;
padding: 10px;
background-color: #4CAF50;
color: white;
border-radius: 4px;
opacity: 0.9;
}
.copy-notification.error {
background-color: #f44336;
}
// usage
const Clipboard = createClipboard();
const copyButton = document.getElementById("copy-buuton");
const textarea = document.getElementById("copy-text");
copyButton.addEventListener("click", () => {
const copyText = textarea.value;
Clipboard.copy(copyText, {
// showNotification: false,
// notificationTimeout: 5000,
callback: (success) => {
if (success) {
console.log("Copy succeeded");
// your code here
} else {
console.log("Copy failed");
}
}
});
});
// usage code inner text copy
const copyCodeButton = document.getElementById("copy-code-button");
const preCode = document.getElementById("copy-code-text");
copyCodeButton.addEventListener("click", () => {
const copyText = preCode.innerText;
Clipboard.copy(copyText, {
notificationTimeout: 1000, // 1 second
});
});
Preview live test
Browser Compatibility
This createClipboard() function support all browsers
browser compatibility table for the Clipboard API and execCommand method
Feature | Chrome | Firefox | Safari | Edge | IE |
---|---|---|---|---|---|
Clipboard API | 66+ | 63+ | 12.1+ | 79+ | No |
document.execCommand | 42+ | 41+ | 10+ | 12+ | 9+ |