Reputation: 19368
So I dont understand why the console logs 1 right away onload or something when i have one.onclick = alterIt(1)
shouldn't it wait till i click one
. Anyway, obviously I am not ver good at javascript, thanks for your help.
window.onload = initialize;
function initialize() {
if (1 == 1){
calculation();
}
}
function calculation() {
var one = document.getElementById('one');
one.onclick = alterIt(1);
}
function alterIt(x) {
console.log(x);
}
Upvotes: 1
Views: 106
Reputation: 266
There are two ways that you could code to work around this issue:
//Anonymous Closures
one.onclick = function(){ alterIt(1); };
//Bind Closures
one.onclick = alertIt.bind(window, 1);
Note: Function.bind() is supported by all the browsers for a year. If you care about old browsers, anonymous closures is the way to go.
Upvotes: 2
Reputation: 16851
When the line one.onclick = alterIt(1);
is executed, alterIt(1)
is actually evaluated. What you want is to bind a function to one.onclick
, which is only executed when the onclick
event fires. You need something like
one.onclick = function() { alterIt(1) };
which doesn't bind the result of alterIt(1)
to one.onclick
, but rather the result of the function evaluation.
Upvotes: 4
Reputation: 16380
What is happening is that you are calling the alterIt
function when you should just be passing it in. So remove the parenthesis like so:
one.onclick = alterIt;
Upvotes: -2
Reputation: 10572
Wrap the function call like this so it doesn't fire until click:
window.onload = initialize;
function initialize() {
if (1 == 1){
calculation();
}
}
function calculation() {
var one = document.getElementById('one');
one.onclick = function(){ alterIt(1);};
}
function alterIt(x) {
console.log(x);
}
Example fiddle: http://jsfiddle.net/RkH6Q/
Upvotes: 2
Reputation: 303321
When you wrote:
one.onclick = alterIt(1);
...then you invoked the alterIt
function and set the return value as the onclick
handler. Instead, you wanted:
one.onclick = function(){ alterIt(1) };
// ...or better yet
one.addEventListener('click',function(){ alterIt(1) },false);
Upvotes: 9