Copy Button for Text Under Pre Tag

 <pre id="textToCopy">Hello</pre>

<button onclick="copyText()">Copy Text</button>



<script>

function copyText() {

    var textToCopy = document.getElementById("textToCopy");

   

    // Create a range object to select text inside the pre tag

    var range = document.createRange();

    range.selectNode(textToCopy);

    window.getSelection().removeAllRanges(); // Clear any previous selection

    window.getSelection().addRange(range); // Select the text

    

    // Copy the selected text

    document.execCommand("copy");

    

    // Deselect the text

    window.getSelection().removeAllRanges();

    

    // Notify the user

    alert("Text copied!");

}

</script>


Previous Post
No Comment
Add Comment
comment url