Reputation: 73
I created the following function using p5.js and the mousePressed method is firing immediately when the page loads. It doesn't wait for me to click the button object to display a paragraph containing the ans variable.
What am I doing wrong?
function setup() {
var ans = generate();
var checkMe = createButton('Check Answer');
checkMe.mousePressed(createP(ans));
}
Upvotes: 0
Views: 198
Reputation: 42176
Let's take a closer look at this line:
checkMe.mousePressed(createP(ans));
This could be split into two lines:
var createPValue = createP(ans);
checkMe.mousePressed(createPValue);
In other words, you're calling the createP()
function, and then passing the value returned (which is probably undefined
) into the mousePressed()
function. I'm surprised this doesn't cause an error in the JavaScript console.
Instead, what you want to do is pass a function as a value into the mousePressed()
function. Since you need to use a parameter, you might do that this way:
function callCreateP(){
createP(ans);
}
checkMe.mousePressed(callCreateP);
Notice that callCreateP
doesn't have parentheses ()
after its name when we pass it into the mousePressed()
function. That's because we're using it as a value instead of directly calling it.
You could shorten that to this line:
checkMe.mousePressed(function(){ createP(ans); });
Upvotes: 1