The changed() function is fired whenever the value of an element gets changed. It can be used to detect changes in checkbox elements or select elements. It can also be used to attach an event listener to an element.
Syntax:
changed(fxn)
Parameters: This function accepts a single parameter as mentioned above and described below.
- fxn: This is the callback function that would be called whenever a change is detected. It can be passed ‘false’, which would prevent the previous firing function to stop firing.
Below examples illustrates the changed() function in p5.js:
Example 1: Detecting changes in a checkbox element
let red = 0; let green = 0; let blue = 0; function setup() { createCanvas(600, 300); // create input boxes redCheckbox = createCheckbox( 'Red' , false ); redCheckbox.position(20, 40) redCheckbox.changed(redChanged); greenCheckbox = createCheckbox( 'Green' , false ); greenCheckbox.position(100, 40) greenCheckbox.changed(greenChanged); blueCheckbox = createCheckbox( 'Blue' , false ); blueCheckbox.position(180, 40) blueCheckbox.changed(blueChanged); } function draw() { clear() // change the fill color based // on current rgb the values fill(red, green, blue); rect(20, 80, 300, 300); textSize(20); text( "Check the boxes to change the fill color" , 10, 20); } // functions for each of the colors function redChanged() { if ( this .checked()) red = 128; else red = 0; } function greenChanged() { if ( this .checked()) green = 128; else green = 0; } function blueChanged() { if ( this .checked()) blue = 128; else blue = 0; } |
Output:
Example 2: Detecting changes in a select element
let red = 0; let green = 0; let blue = 0; function setup() { createCanvas(350, 300); textSize(18) text( "Select the color to change the background color" , 10, 20); // create select element selectElem = createSelect(); selectElem.position(20, 40); selectElem.option( 'Slecet' ); selectElem.option( 'Red' ); selectElem.option( 'Green' ); selectElem.option( 'Blue' ); selectElem.changed(changeColor); } function changeColor() { clear(); colorVal = this .value(); if (colorVal == "Red" ) { background( "red" ); } else if (colorVal == "Green" ) { background( "green" ); } else if (colorVal == "Blue" ) { background( "blue" ); } else background(128); text( "Select the color to change the background color" , 10, 20); } |
Output:
Online editor: https://editor.p5js.org/
Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
Reference: https://p5js.org/reference/#/p5/changed