Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this javascript function running without being called?

$(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?

like image 890
jamone Avatar asked Jul 02 '10 14:07

jamone


2 Answers

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.

like image 50
Pointy Avatar answered Oct 06 '22 00:10

Pointy


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).

like image 44
SLaks Avatar answered Oct 06 '22 01:10

SLaks