Sending Values Between Functions

I am trying to use the p5js.gui library to collect a simple text input and then just output that input to the screen. I have tried a number of different approaches but keep running into errors. This is what I have so far.

let button;

function setup() {
  var inp = createInput('');
  inp.position(100,100);
  newInput = inp.input(myInputEvent);
  button = createButton('click me');
  button.position(19, 19);
  button.mousePressed(changeText(newInput));
  createCanvas(500, 500);
}

function myInputEvent() {
  //console.log('you are typing: ', this.value());
  var myInput = this.value();
  return myInput;
}

function changeText(nextInput){
  text (nextInput, 100, 200);
}

I have had some success by moving the text output to the myInputEvent() function but it prints it out as I am entering into the text field. I want to print out only when the button is clicked.
I believe the issue might be that I am not properly passing the value from one function to another, but am not really sure.
Any help is appreciated.

1 Like

You are passing to mousePressed() what is returned by invoking changeText(newInput) at that moment; which is undefined.

Instead, you need to pass the callback itself: button.mousePressed(changeText);

We can’t control when it’s invoked nor what is passed to a callback.

In order to access the variable inp anywhere, declare it globally, just like you did to button:
let button, inp;

Then you can access it inside changeText() callback:

function changeText() {
  text(inp.value(), 100, 200)
}
2 Likes

Thank you so much, that really helped. Here is the working code in case anyone else needs it as reference.

//global variables
let button;
let inp;

function setup() {
  inp = createInput('');
  inp.position(100,100);
  newInput = inp.input(myInputEvent);
  button = createButton('click me');
  button.position(19, 19);
  button.mousePressed(changeText);
  createCanvas(500, 500);
}

function myInputEvent() {
  var myInput = this.value();
  return myInput;
}

function changeText(){
  text (inp.value(), 100, 200);
}
1 Like