var pickEvent
var img;
var img2;
var img3;
var sel;
var sel1;
var title;
var bill;
var answer;
var output;
// preload some images
function preload() {
img = loadImage('mandarin.jpg');
img2 = loadImage('bostonpizza.jpg');
img3 = loadImage('nandos.jpg');
}
function setup() {
title = createElement('h1', 'Tip calculator'); // Create the main title for the question
title.position(265, 40); // Set the position of the title
createCanvas(900, 500);
bill = createInput(); // Create the input box for the user to enter a number
bill.position(312, 175); // Set the position of the input box
textAlign(CENTER);
background(200);
sel = createSelect();
sel.position(315, 110);
sel.option('Mandarins');
sel.option('Nandos');
sel.option('Boston Pizza');
sel.selected(pickEvent);
textAlign(CENTER);
background(200);
sel1 = createSelect();
sel1.position(325, 245);
sel1.option('Very Bad');
sel1.option('Bad');
sel1.option('Okay');
sel1.option('Good');
sel1.option('Great');
sel1.option('Excellent');
sel1.option('Random Amount');
sel1.selected('Service');
output = createElement('h3', "") // Creating a placeholder for the final output
button = createButton('tip it'); // Create a button and the name inside the button
button.position(345, 285); // Set the position of the button
button.mousePressed(calculation); // When the mouse button is pressed on the button it goes to the calculation function
}
function draw() {
background(153);
let pickEvent = sel.value()
if (pickEvent == 'Mandarins') {
background(img);
}
if (pickEvent == 'Nandos') {
background(img3);
}
if (pickEvent == 'Boston Pizza') {
background(img2);
}
// Calculate the conversion
function calculation() {
let conversion = sel1.value(); // Set the drop down menu option to the variable conversion
//convert fahrenheit to celsius
if (sel1 == ('Very Bad')) { // Run this if the selection is set to F to C
answer = round(((bill.value() * .01), 2)) // Math to convert
total = answer + bill.value()
output.html('This is the answer: ' + answer + '\u2103') // Create the screen output for the user. \u2103 is the HTML CSS degrees C symbol
output.position(315, 500) // Set the position of the answer
}
}
}
This is how you code should look like formatted with proper indentation. When coding, indentation is really important as it gives you a visual clue of what is where.
And here, you can clearly see calculation() is defined in draw(). So it’s valid only inside of draw(). You need to get it out to be able to use it in other places.
Also if you are using the p5.js web editor, you can auto format your code by clicking Edit -> Tidy code