0

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/

2 Answers 2

3

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);
});
Sign up to request clarification or add additional context in comments.

8 Comments

that's why jQuery is always a better way to this kind of stuff in IE~ $("myButton").on("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); I know someone will mention jquerry i just knew it...
@redacted look, you used parentheses again. You can't do that, because it invokes the function. Editing...
@redacted see my edit. But seriously, what's your reason for not using some sort of cross-browser library? If you loathe jQuery and the fanboys (myself included) there are plenty others to choose from.
Actually myButton.onclick = open_close; worked even on IE 6.0 i just checked on virtual PC so i don't see problem there. Reason is i like to have pure code that i wrote and no extra files to download. I am minimalist i guess.
|
1

Replace open_close() with open_close

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

1 Comment

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

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.