Below is a complete HTML file that defines a <copy-button> custom element. This web component uses a clipboard emoji (📋) on its button, emits a "copy" custom event when clicked, and provides two API methods:
copyText(text) – Receives text, attempts to copy it using the modern async Clipboard API (with a fallback), and then signals success.
copySuccess() – Updates the button’s appearance for a short time (2 seconds) to indicate that the copy was successful.
You can copy the code into a file (e.g. index.html), open it in your browser, and click the button to test it.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Copy Button Component Demo</title>
</head>
<body>
<!-- Use the custom element -->
<copy-button id="my-copy"></copy-button>
<script>
class CopyButton extends HTMLElement {
constructor() {
super();
// Attach a shadow DOM for encapsulation.
this.attachShadow({ mode: "open" });
// Create a button element
this._button = document.createElement("button");
this._button.innerText = "📋"; // clipboard icon emoji
this._button.style.cursor = "pointer";
// Add some basic styling and transition effects.
this._button.style.transition = "background-color 0.3s, color 0.3s";
this.shadowRoot.appendChild(this._button);
this._resetTimeout = null;
}
connectedCallback() {
// When the button is clicked, emit a "copy" event.
this._button.addEventListener("click", () => {
const event = new CustomEvent("copy", {
bubbles: true,
composed: true,
});
this.dispatchEvent(event);
});
}
/**
* Copies the provided text to the clipboard using the modern async API
* if available, with a fallback for older browsers.
*
* @param {string} text The text to copy.
*/
async copyText(text) {
try {
if (navigator.clipboard && navigator.clipboard.writeText) {
await navigator.clipboard.writeText(text);
} else {
// Fallback method: create a hidden textarea.
const textarea = document.createElement("textarea");
textarea.value = text;
// Avoid scrolling to bottom & keep textarea invisible.
textarea.style.position = "fixed";
textarea.style.top = "0";
textarea.style.left = "0";
textarea.style.opacity = "0";
document.body.appendChild(textarea);
textarea.focus();
textarea.select();
const successful = document.execCommand("copy");
document.body.removeChild(textarea);
if (!successful) {
throw new Error("Fallback: Copying command unsuccessful");
}
}
// If copy is successful, signal success visually.
this.copySuccess();
} catch (err) {
console.error("Failed to copy text: ", err);
}
}
/**
* Changes the button’s appearance temporarily to signal that the copy was successful.
*/
copySuccess() {
// Remember original icon/text.
const originalText = "📋";
// Change to a success icon.
this._button.innerText = "✅";
this._button.style.backgroundColor = "#4caf50"; // green background
this._button.style.color = "white";
// Reset after 2 seconds.
if (this._resetTimeout) {
clearTimeout(this._resetTimeout);
}
this._resetTimeout = setTimeout(() => {
this._button.innerText = originalText;
this._button.style.backgroundColor = "";
this._button.style.color = "";
}, 2000);
}
}
customElements.define("copy-button", CopyButton);
// Example usage:
// When the "copy" event is fired (i.e. when the button is clicked),
// call copyText() with the text you want to copy.
const copyButton = document.getElementById("my-copy");
copyButton.addEventListener("copy", () => {
// Replace 'Hello, World!' with the desired text.
copyButton.copyText("Hello, World!");
});
</script>
</body>
</html>
How It Works
-
Custom Element Definition:
The CopyButton class extends HTMLElement and uses shadow DOM for style encapsulation.
-
Button Click & Event Emission:
When the button is clicked, it emits a "copy" event. In the demo usage, an event listener on the <copy-button> element then calls the copyText() function with some sample text.
-
Copying Text:
The copyText(text) function uses navigator.clipboard.writeText if available. If not, it falls back to creating a hidden <textarea> element and using document.execCommand("copy").
-
Success Feedback:
On successful copy, the copySuccess() method changes the button to show a checkmark emoji (✅) with a green background for 2 seconds before reverting.
This implementation provides both the needed API functions and the visual feedback to let users know the text was copied successfully.