my copy to clipboard code in JavaScript doesn't work

im a beginner. this is the first real application i tried to write in javascript and i would love to understand why it doesn’t work?

var button = document.getElementById("button");
var text = document.getElementById("text");
function button() {;
 text.setSelectionRange(0, 99999); 
alert("you copied this text");

button is a onclick event in html and text is an input in html.
thank you very much

  • Rename the function to another name. buttonC

  • Write the script at the end of the html because it should load when the elements are already defined.

  • Use then and catch for navigator.clipboard to catch possible errors.

<button id="button" onclick="buttonC()">Copy</button>
<input type="text" id="text" class="text">
<script type="text/javascript">
    var text = document.getElementById("text");
    function buttonC() {;
            .then(() => {
            .catch(err => {
                console.log('Something went wrong', err);
        //alert("you copied this text");

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.