About this snippet

Implement a "copy to clipboard" feature for text content using modern JavaScript. Useful for sharing code snippets, links, or any text data easily.

Size
1.4 KB
Uses
HTML, CSS, JavaScript
Loads
Nothing external
Views
295
<input type="text" id="textToCopy" value="Hello, World! This text can be copied.">
<button id="copyButton">Copy Text</button>
<p id="copyStatus"></p>
input#textToCopy {
  width: 250px;
  padding: 8px;
  margin-right: 5px;
}
button#copyButton {
  padding: 8px 12px;
  cursor: pointer;
}
#copyStatus {
  margin-top: 5px;
  font-size: 0.9em;
  color: green;
}
const copyButton = document.getElementById('copyButton');
const textToCopy = document.getElementById('textToCopy');
const copyStatus = document.getElementById('copyStatus');

copyButton.addEventListener('click', () => {
  if (navigator.clipboard && navigator.clipboard.writeText) {
    navigator.clipboard.writeText(textToCopy.value)
      .then(() => {
        copyStatus.textContent = 'Copied to clipboard!';
        setTimeout(() => { copyStatus.textContent = ''; }, 2000);
      })
      .catch(err => {
        copyStatus.textContent = 'Failed to copy!';
        console.error('Failed to copy text: ', err);
        // Fallback for older browsers can be added here if needed
      });
  } else {
    // Fallback for older browsers (less secure, might not always work)
    textToCopy.select();
    try {
      document.execCommand('copy');
      copyStatus.textContent = 'Copied to clipboard! (fallback)';
    } catch (err) {
      copyStatus.textContent = 'Failed to copy! (fallback)';
    }
    window.getSelection().removeAllRanges(); // Deselect
    setTimeout(() => { copyStatus.textContent = ''; }, 2000);
  }
});
Esc
↑↓ moveEnter select

Start from a template

Open an .html file, or HTML, CSS, JS, Markdown, Less or TypeScript files. You can also drop them here. Styles and scripts go into their panes.

Share

Source

Keyboard shortcuts

Save