JavaScript Copy Text To Clipboard

JavaScript Copy Text To Clipboard without an input box and with an input box. We can use this snippet as a copy URL to the clipboard and show the user the link copied to the clipboard. Here, JavaScript Copy Text To Clipboard will be executed after the page load and then you can copy text or URL by clicking on the copy button.

HTML

<div class="content-middle">
    <textarea class="copyTextArea">Copy this content by click on the copy button</textarea>
    <button class="copyTextBtn" onclick='this.innerHTML = "Copied"'>Copy</button>
</div>

CSS

* {
    box-sizing: border-box;
}
.content-middle {
    width: 90%;
    margin: 50px auto;
    display: table;
}
.content-middle .copyTextArea {
    width: 100%;
    max-width: 100%;
    min-height: 150px;
    font-size: 22px;
    padding: 15px;
    border-radius: 4px;
    border: 1px solid #ddd;
    box-shadow: 0px 0px 8px 0px #adadad;
}
.copyTextBtn {
    float: right;
    padding: 8px 20px;
    font-size: 20px;
    border: none;
    background-color: #2196F3;
    color: #fff;
    border-radius: 4px;
    margin-top: 25px;
    box-shadow: 0px 0px 8px 0px #adadad;
    cursor: pointer;
}

JavaScript

// Function execute after the window load
window.onload = function () {
var copyTextBtn, copyTextArea

copyTextBtn = Array.prototype.slice.call(document.querySelectorAll('.copyTextBtn'));
copyTextArea = Array.prototype.slice.call(document.querySelectorAll('.copyTextArea'));

  copyTextBtn.forEach(function(copybtn, copyTxt){
    copybtn.addEventListener("click", function(){
        copyTextArea[copyTxt].select();
        try {
            var successful = document.execCommand('copy');
        } catch (copyTxt) { }
    });            
  });
}