Reputation: 17421
$(document).ready(SetupButtonClicks());
function SetupButtonClicks() {
$('#btnJavaPHP').click(DoPHPStuff());
}
function DoPHPStuff() {
//stuff
}
I have this code in my javascript file, when I debug it I see it call SetupButtonClicks()
like it should but after that is done it calls DoPHPStuff()
. DoPHPStuff()
should only be called when btnJavaPHP
is clicked. What am I doing wrong?
Upvotes: 5
Views: 5230
Reputation: 413709
Change your SetupButtonClicks function:
$('#btnJavaPHP').click(DoHPStuff);
The way you've got it coded, you're telling Javascript to call the function, not to use it as the "click" handler. The parentheses are an operator that causes a function to be called.
Upvotes: 17
Reputation: 792
With the exception of a function declaration, a pair of parentheses following a function's identifier causes the function to execute. Examples:
// function declaration; function not executed
function SetupButtonClicks() {
}
// function executed
SetupButtonClicks();
// function not executed
SetupButtonClicks;
Upvotes: 2
Reputation: 50109
function DoPHPStuff() {
//stuff
}
function SetupButtonClicks() {
$('#btnJavaPHP').click(DoPHPStuff);
}
$(document).ready(SetupButtonClicks);
Upvotes: 3
Reputation: 887413
Remove the ()
.
By writing $(document).ready(SetupButtonClicks())
, you are calling SetupButtonClicks
and passing its return value to ready
.
Similarly, by writing $('#btnJavaPHP').click(DoPHPStuff())
, you are calling DoPHPStuff
(immediately) and passing whatever it returns to click()
.
You need to pass the functions themselves by writing $(document).ready(SetupButtonClicks)
and $('#btnJavaPHP').click(DoPHPStuff)
.
Upvotes: 3