Skip to content

Latest commit

 

History

History
22 lines (14 loc) · 835 Bytes

how_do_you_create_copy_to_clipboard_button.md

File metadata and controls

22 lines (14 loc) · 835 Bytes

How do you create copy to clipboard button?

You can create a 'copy to clipboard' button using the document.execCommand('copy') method. However, modern browsers prefer using the Clipboard API for better security and compatibility.

Example using Clipboard API:

let copyButton = document.querySelector('#copyButton');
let textToCopy = document.querySelector('#textToCopy');

copyButton.addEventListener('click', () => {
  navigator.clipboard.writeText(textToCopy.textContent)
    .then(() => { console.log('Text copied to clipboard!'); })
    .catch(err => { console.log('Failed to copy text:', err); });
});

Tags: intermediate, JavaScript, DOM