Uncaught TypeError: t is undefined (p5.min.js:4604:988), when trying to use button.mousePressed

I’m making a generator for rooms, and it takes in 3 arguments - number of rooms, min size, and max size of the rooms generated. The code works fine when I try to hard code it:

function setup() {      
    createCanvas(1280, 512);      
    //randomly creates x rooms of different sizes
    generator = new Room_map(5, 10, 15);
    //draw these rooms 

But when I try to take in user input using this example here examples | p5.js, the above error shows up in the console.

Any help is apprieciated. Thanks in advance!

Here is my code for taking in user input:

function setup() {    
    createCanvas(1024, 512);

    input_no_of_rooms = createInput();    //no of rooms
    input_no_of_rooms.position(1100, 50);

    input_min_size = createInput();        //min size
    input_min_size.position(1100, 90);

    input_max_size = createInput();        //max size
    input_max_size.position(1100, 130);

    button = createButton('Generate');
    button.position(1100, 155);

    //when button is pressed, call gen function with the above inputs

function gen(no, min, max)
    if (no > 0 && min > 0 && max > 0)
        console.log("generating"); //does not show up in log after pressing button

        //randomly creates x rooms of different sizes
        var generation = new Room_map(no, min, max);

        //draw these rooms 
1 Like

Hi @kewyj,

Welcome to the forum! :wink:

Remember to format your code by using the </> button when editing a message on the forum.

If you check the p5.Element.mousePressed() reference, it says this:

  • Syntax:

  • Parameters

    fxn - Function|Boolean:

    function to be fired when mouse is pressed over the element. if false is passed instead, the previously firing function will no longer fire.

So it’s expecting either a function or a boolean but in your code you are actually providing the return value of your gen function.

Let me explain:

When the JS engine executes your code, it reads this:


It’s a method call so it first evaluates the parameters which are:


and this is a function call to the gen function so it runs that function and store its result. The thing is that your gen function doesn’t return anything so by default it’s returning undefined.

And undefined is not a function! So when you press the button it fails to call that function.

So what is the solution here?

Two things:

  • If your function wasn’t taking any arguments or you didn’t care about them, you could just put the name of the function like this:

  • On the other side, if you need to pass some arguments you can either bind() the function with the parameters:

    button.mousePressed(myFunction.bind(null, arg1, arg2, arg3));

    Or simpler use an arrow function:

    button.mousePressed(() => myFunction(arg1, arg2, arg3));

Have fun! :yum: