Home > Back-end >  Onclick function in the <script> tag instead of the <button> not working
Onclick function in the <script> tag instead of the <button> not working

Time:09-13

I'm trying to use the onClick() function inside the script tag.

<!DOCTYPE html>
<html>
    <head>
        <script>
        const btn = document.getElementById("mainButton");
        btn.onclick = function(){
            alert("You shouldn't have clicked this button!");
        };
        </script>
    </head>
    <body>
        <button id="mainButton">Do not click this button</button>
    </body>
</html>

When I looked on the internet to find the syntax to do this it looked something like the above.

However when I run this script it doesn't work and I have no clue why and Any other way I've tried becomes a syntax error.

CodePudding user response:

You need to use defer or move the script tag to the end of the body.

<!DOCTYPE html>
<html>
    <head>
        <script>
        document.addEventListener('DOMContentLoaded', () => {
         const btn = document.getElementById("mainButton");
        btn.onclick = function(){
            alert("You shouldn't have clicked this button!");
        };
        });
       
    </script>
    </head>
    <body>
        <button id="mainButton">Do not click this button</button>
        
    </body>
</html>

<!DOCTYPE html>
<html>
    <head>
       
    </head>
    <body>
        <button id="mainButton">Do not click this button</button>
         <script>
        const btn = document.getElementById("mainButton");
        btn.onclick = function(){
            alert("You shouldn't have clicked this button!");
        };
    </script>
    </body>
</html>

  • Related