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/
Ah, but you did run it:
Parentheses invoke a function. Use this instead:
Better still (click through for legacy IE support):
You still cannot use parentheses as you keep trying to do, because parentheses invoke the function. Use an anonymous function: