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.select();
 text.setSelectionRange(0, 99999); 
navigator.clipboard.writeText(text.value);
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() {
        text.select();
        navigator.clipboard.writeText(text.value.trim())
            .then(() => {
                console.log('Copied')
            })
            .catch(err => {
                console.log('Something went wrong', err);
            })
        //alert("you copied this text");
    }
</script>