1

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?

2 Answers 2

3

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

$(document).ready(main);
Sign up to request clarification or add additional context in comments.

Comments

3

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

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

=>

$(document).ready(main);

1 Comment

facepalm Makes perfect sense, once I think about it. Thanks for quick answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.