clipboardCopy.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. export default function handleClipboardCopy() {
  2. const copyInputs = document.querySelectorAll('.js-copy-input');
  3. const copyButtons = document.querySelectorAll('.js-copy-button');
  4. // Iterate over each input and button pair
  5. copyInputs.forEach((copyInput, index) => {
  6. let inputFocused = false;
  7. // Ensure corresponding button exists
  8. if (!copyButtons[index]) {
  9. return;
  10. }
  11. const copyButton = copyButtons[index];
  12. // Copy on focus and allow for partial selection
  13. copyInput.addEventListener('click', () => {
  14. if (!inputFocused) {
  15. copyInput.select();
  16. inputFocused = true;
  17. // Reset inputFocused when input loses focus
  18. copyInput.addEventListener(
  19. 'blur',
  20. () => {
  21. inputFocused = false;
  22. },
  23. { once: true },
  24. );
  25. }
  26. });
  27. // Copy to clipboard on button click
  28. copyButton.addEventListener('click', () => {
  29. navigator.clipboard.writeText(copyInput.value).then(() => {
  30. // Temporarily change button content
  31. const buttonIcon = copyButton.innerHTML;
  32. copyButton.innerHTML = 'Copied!';
  33. copyButton.disabled = true;
  34. // Revert button content after 2 seconds
  35. setTimeout(() => {
  36. copyButton.innerHTML = buttonIcon;
  37. copyButton.disabled = false;
  38. }, 2000);
  39. });
  40. });
  41. });
  42. }