/ Web Development

كيف عملت خاصية النسخ في الموقع

Creator Image
Bashar Alshaibani
30 May 2024 -
دقيقتان قراءة
<script>
        document.addEventListener('DOMContentLoaded', function() {
        var codeElements = document.querySelectorAll('pre code'); // Assuming each <code> is inside a <pre>
        codeElements.forEach(function(codeElement, index) {
        // Assign a unique ID to each code element
        var uniqueId = 'codeBlock' + index;
        codeElement.id = uniqueId;

        // Optional: Create and append a copy button
        var copyButton = document.createElement('button');
        copyButton.innerText = 'Copy';
        copyButton.className = 'copyButton';
        copyButton.onclick = function() { copyCode(uniqueId); };
        copyButton.addEventListener('click', function() {
            copyButton.innerText = 'Copied!';
            setTimeout(function() {
                copyButton.innerText = 'Copy';
            }, 1000);
        });
        // Assuming each <code> tag is wrapped in a <pre>, insert the button before the <pre>
        codeElement.parentNode.style.position = 'relative';
        codeElement.parentNode.insertBefore(copyButton, codeElement);
        });
    });
    
    function copyCode(elementId) {
        var text = document.getElementById(elementId).innerText;
        navigator.clipboard.writeText(text).then(function() {
        }, function(err) {
            console.error('Could not copy text:', err);
        });
    }
</script>