Add a copy button to div container

This snippet will let you copy text from a specific div (in my case „.syntaxhighlighter“) with a button. You need to implement a button and provide an ID for that button.
I am using this snippet right here on this page. 🙂

<script>
    
function loadEvent() {
           document.getElementById("copyCode").addEventListener("click", copyElementText); //replace copyCode with your button ID
           console.log("loaded");
        }
window.onload = loadEvent;

function copyElementText(id) {
    var text = document.querySelector(".syntaxhighlighter").innerText; //replace .syntaxhighliter with your selector
    var elem = document.createElement("textarea");
    document.body.appendChild(elem);
    elem.value = text;
    elem.select();
    document.execCommand("copy");
    document.body.removeChild(elem);
    console.log("Yeah");
    // document.querySelector("#copyCode > span > span.elementor-button-text").innerText = "copied !";
    setTimeout( function() {
        // document.querySelector("#copyCode > span > span.elementor-button-text").innerText = "copy code";
    }, 2000);


}
</script>

WHERE TO PLACE THIS CODE?

Place this snippet on the same page as your „to copy“ content.
If using WordPress, you could place it within an html block, if using Elementor within an html widget.

Pleasure?

Please share your thumbsup, suggestions, edits, and questions within my comment section down there. 

I love posting snippets for you, but with a bit of feedback, it gets even more fun. 😀

Sharing is caring:

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert