Reputation: 103
This function gets called on page load, not when .somebutton is clicked. I'm not sure why. I want to be able to pass the variables so that I may use this function in multiple places with different values. Thank you very much.
var i = "this be i";
var u = "this be u";
function dosomething (var1, var2){
console.log(var1 + " and " + var2);
}
$(".somebutton").click(dosomething(i,u));
Upvotes: 4
Views: 417
Reputation: 53531
In JavaScript doing
$(".somebutton").click(dosomething(i,u));
will not assign the function to your click event, but will rather call the function and assign whatever result the function returns. You need to reference your function instead :
$(".somebutton").click(dosomething);
If you need to pass variables to your function, then you need to wrap the said function inside another anonymous one :
$(".somebutton").click(function() { dosomething(i, u); });
Upvotes: 1
Reputation: 337560
You can only pass a function by reference using the method in your example (ie. without parameters). The reason your function works on load is because it is immediately invoked due to the trailing ()
brackets.
If you need to pass parameters you need to wrap it in an anonymous function, like this:
// on click:
$(".somebutton").click(function() {
dosomething(i, u);
});
// on page load:
dosomething(i, u);
Upvotes: 1
Reputation: 27584
You are passing value returned by dosomething(i,u)
to click
handler. This is why it ise executing without clicking, it is happening as soon as you call your function (that is: dosomething(i,u)
). You need to wrap your function call inside anonymous function:
$(".somebutton").click(function() { dosomething(i,u); } );
Upvotes: 6