javascript function running without being called

pwp picture pwp · Feb 12, 2013 · Viewed 18.8k times · Source

I wonder why, as soon as the page loads, the function btw_bijtellen () is called. I wanted to call it by clicking...

var $ = function (id) {
    return document.getElementById (id);
}

function btw_bijtellen () {
    window.alert("we want to calculate something after clicking th button");
}

$("bereken").onclick = btw_bijtellen ();

Answer

Lloyd picture Lloyd · Feb 12, 2013

You've added () which causes the function to execute.

For example:

var myFunc1 = function() {
    alert('Hello');
}(); // <--- () causes self execution

var myFunc2 = function() {
    return 5 + 5;
};

var some_value = myFunc2(); // <--- Again () causes execution (you'd expect this one)

In your case, as mentioned in comments you're basically telling the onclick to set its value to the return value of the function.

If you drop the () it should run as expected.