code-copy.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. function copyCode(button) {
  2. const codeBlock = button.closest('.code-block-container').querySelector('.code-content');
  3. // Get the actual code content, excluding any highlight tags
  4. const preElement = codeBlock.querySelector('pre');
  5. const code = preElement ? preElement.textContent : codeBlock.textContent;
  6. const tooltip = button.querySelector('.tooltip');
  7. // Create a temporary textarea to copy the text
  8. const textarea = document.createElement('textarea');
  9. textarea.value = code.trim();
  10. document.body.appendChild(textarea);
  11. textarea.select();
  12. try {
  13. document.execCommand('copy');
  14. button.classList.add('copied');
  15. tooltip.textContent = 'Copied!';
  16. // Fallback to modern clipboard API if available
  17. if (navigator.clipboard) {
  18. navigator.clipboard.writeText(code.trim()).catch(() => {});
  19. }
  20. setTimeout(() => {
  21. button.classList.remove('copied');
  22. tooltip.textContent = '';
  23. }, 2000);
  24. } catch (err) {
  25. console.error('Failed to copy:', err);
  26. tooltip.textContent = 'Failed to copy';
  27. button.classList.add('copied');
  28. setTimeout(() => {
  29. button.classList.remove('copied');
  30. tooltip.textContent = '';
  31. }, 2000);
  32. } finally {
  33. document.body.removeChild(textarea);
  34. }
  35. }