Why does this javascript function work without a call?

$(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 that it calls SetupButtonClicks(), as it should, but after that it calls DoPHPStuff(). DoPHPStuff()should be called only when pressed btnJavaPHP. What am I doing wrong?

+5
source share
4 answers

Change the function SetupButtonClicks:

$('#btnJavaPHP').click(DoHPStuff);

As you encoded it, you are telling Javascript to call the function, not to use it as a "click" handler. Brackets are an operator that calls a function call.

+17
source

Remove ().

$(document).ready(SetupButtonClicks()), SetupButtonClicks ready.
, $('#btnJavaPHP').click(DoPHPStuff()), DoPHPStuff () , , click().

, $(document).ready(SetupButtonClicks) $('#btnJavaPHP').click(DoPHPStuff).

+3
function DoPHPStuff() {
    //stuff
}

function SetupButtonClicks() {
    $('#btnJavaPHP').click(DoPHPStuff);
}

$(document).ready(SetupButtonClicks);    
+3
source

With the exception of the declaration of the function, a pair of brackets following the identifier of the function calls the execution of the function. Examples:

// function declaration; function not executed
function SetupButtonClicks() {

}

// function executed
SetupButtonClicks();

// function not executed
SetupButtonClicks;
+2
source

All Articles