cvdellen
cvdellen

Reputation: 241

Javascript functions within Dojo script run without being called

I am feeling quite stupid about this, but I have a named function within my main Dojo require script that my intention was to run when called by a click event. However, the function runs on loading the page and does not run on the click event.

<script>
require(["esri/map", "dojo/domReady!"], function(Map){
    var map = new Map("map");
    testNode = document.getElementById("testNode");
    testNode.onclick = test();

    function test() {
        alert("test");
    }
}
</script>

<body>
    <div id="testNode">Click Here To Test</div>
    <div id="map></div>
</body>

As soon as the page loads the "test" alert pops up and nothing happens on the click event.

Upvotes: 1

Views: 120

Answers (1)

Patrik Oldsberg
Patrik Oldsberg

Reputation: 1550

When you type

testNode.onclick = test();

You're calling the function test and passing the return value of the function to testNode.onclick. You should instead assign a reference of the function test to testNode.onclick:

testNode.onclick = test;

Upvotes: 4

Related Questions