Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Onclick function in the <script> tag instead of the <button> 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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading