Skip to content
Advertisement

Onclick function in the tag instead of the not working

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.

Advertisement

Answer

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>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement