ViggyNash
ViggyNash

Reputation: 611

Jquery event handler works only with anonymous function?

I have some jQuery that changes a bit of text when a button is clicked. This code works fine when implemented within an anonymous function (nn_list is a globally defined array of strings, nn_flag predefined as false):

$(document).ready(function(){
    $("#nn_button").click(function(){
        $('.nickname').empty();

        var random_name = nn_list[Math.floor(Math.random() * nn_list.length)];
        console.log(random_name);
        $('.nickname').append("<p>" + random_name + "</p>");
    });
});

But it doesn't work (doesn't change the text) when I implement it as a non-anonymous function:

var main = function(){
    $("#nn_button").click(function(){
        $('.nickname').empty();

        var random_name = nn_list[Math.floor(Math.random() * nn_list.length)];
        console.log(random_name);
        $('.nickname').append("<p>" + random_name + "</p>");
    });
}
$(document).ready(main());

Can someone explain to me what changes between those two implementations that makes the anonymous function work, but not the other?

Upvotes: 1

Views: 63

Answers (2)

scniro
scniro

Reputation: 16979

Just pass it, don't invoke it. Observe the following....

$(document).ready(main());

=>

$(document).ready(main);

Upvotes: 3

Amit
Amit

Reputation: 46323

You need to pass a reference to the function, not call it:

$(document).ready(main);

Upvotes: 3

Related Questions