redacted
redacted

Reputation: 453

JavaScript function on event running on declaration

Why when i load page it runs function and alerts me "function run" i did not call it nowhere i need function to only trigger on element click.

<script type="text/javascript">

open_close = function() {
   alert("function run");
   //some code ...
}

window.onload = function() {
   //some code ...
   var myButton = document.getElementById('button');
   myButton.onclick = open_close();
   //some code ...
}

</script>

Here's jfiddle demo http://jsfiddle.net/ayeBP/

Upvotes: 0

Views: 100

Answers (2)

Matt Ball
Matt Ball

Reputation: 359786

Ah, but you did run it:

myButton.onclick = open_close();

Parentheses invoke a function. Use this instead:

myButton.onclick = open_close;

Better still (click through for legacy IE support):

myButton.addEventListener('click', open_close);

Okay this was simplidied function i need to actually pass 2 variables to it e.g. myButton.onclick = open_close(var1,var2);

You still cannot use parentheses as you keep trying to do, because parentheses invoke the function. Use an anonymous function:

myButton.onclick = function () {
    open_close(var1, var2);
};

// or, even better,
myButton.addEventListener('click', function () {
    open_close(var1, var2);
});

Upvotes: 3

stewe
stewe

Reputation: 42622

Replace open_close() with open_close

Using parentheses here will invoke the function immediately and assign the return value of it to myButton.onclick

Upvotes: 1

Related Questions