JSON - generating a random value from a certain section with mousePressed()

Working with JSON files - I have to recall a certain value with mousePressed() in a specific category.

In my code you have the following code :

var chuckData;

function setup () {
    createCanvas (displayWidth, 500);
    loadJSON("https://api.icndb.com/jokes/random", getData);
    
}

function draw () {
background(220);
    
    if (chuckData) {
            text(chuckData.value.joke, 10, 200);  
        }
    }



function getData(data) {
    chuckData = data;
}

function mousePressed () {
    text(chuckData.value.joke, 100, 200);
    
}

In this code I load the link --> https://api.icndb.com/jokes/random (clicking the link will highlikely show 1 joke. but changes on refresh)

There is a section called “joke” I need to retrieve a joke from, and then generate it into text on screen.

This being :

if (chuckData) {
            text(chuckData.value.joke, 10, 200);  
        }
    }

I managed to get the text to print on the screen, and it changes the joke on refresh, however: I need to get this effect when using mousePressed() and fail to find out how to do it or find it on the internet.

Any help is appreciated!

with mouse pressed ( released ) you set something, not draw anything…
but that setting can use in draw.

var chuckData;
var thejoke="test: click";

function setup () {
  createCanvas (displayWidth, 500);
  loadJSON("https://api.icndb.com/jokes/random", getData);
}

function draw () {
  background(220);

  if (chuckData) {
    text(thejoke, 10, 200);
  }
}


function getData(data) {
  chuckData = data;
}

function mouseReleased () {
  thejoke = chuckData.value.joke;
}

@kll but how can I get a random joke from the file when continuously clicking?

As I showed in my code: When starting the page, a joke shows.

Continuously clicking should change the joke. Now I am still forced to refresh the page, but now need to click and release to show the joke (when using your example).

how should I tackle that?

must load again i think:

function mouseReleased () {
  loadJSON("https://api.icndb.com/jokes/random", getData);
  thejoke = chuckData.value.joke;
}

I got it, thanks!

What you mentioned about re-loading the JSON in the function seems to work.

I changed it back to

function mousePressed() {

loadJSON("https://api.icndb.com/jokes/random", getData);

}

and that seemed to work. Thank you :slight_smile: