0

Alert: JavaScript beginner here.

<!DOCTYPE HTML>
<html>
    <head>
        <script>
        function mostraralerta() {
            alert("you've clicked!");
        }
        function hacerclic() {
            document.getElementById("boton").onClick = function(){
            mostraralerta();
            };
        }
        window.onLoad=hacerclic();
        </script>
    </head>
    <body>
        <input type="button" id="boton" value="click">
    </body>
</html>

When you click on the input it doesn't shows the alert. If I remove the anonymous function and do it directly:

document.getElementById("boton").onClick = mostraralerta();

or with another selector:

document.querySelector("#boton").onClick = mostraralerta();

It shows the alert as soon as you open the webpage, instead of when clicking the button.

Also I have tried with another html tag instead of an input, but the only way I have made this code to works is to put directly the event onClick on the input, but I'd like to know how to make it works with the functions and onload.

1
  • document.getElementById("boton") return undefined here since your button is not yet in the DOM Commented May 18, 2017 at 10:52

2 Answers 2

5

By including the brackets at the end of mostraralerta you're executing that function and storing the result of it in .onclick What you want to do is pass the name of the function without executing it, like this:

document.getElementById("boton").onclick = mostraralerta;
Sign up to request clarification or add additional context in comments.

Comments

0

document.getElementById("boton") is null when the hacerclic function is called.This is because the input tag is not rendered.You can fix it by moving the window.onload to the end like this

<body>
    <input type="button" id="boton" value="click">
    <script>window.onload= hacerclic();</script>
</body>

And the onclick is all lower case:

 document.getElementById("boton").onclick = function(){
 mostraralerta()
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.