Fields That Affect Other Fields
← All Butter documentationSometimes, you want to use a field to control the value of another field. A common example is a presets field: when a preset is selected, it modifies the values of other fields. Sometimes you may want to show or hide other fields, too, maybe opting to hide the underlying fields until a "custom" preset has been selected. You can do this using the .changed() method on a field.
Call .changed() on a field with a function to run. It runs whenever the field changes. You can also use .input(), which works the same way:
let label
function setup() {
createCanvas(windowWidth, windowHeight)
label = createInput('Hello')
label.changed(() => {
console.log('The text is now', label.value())
})
}
function draw() {
clear()
textAlign(CENTER, CENTER)
textSize(48)
text(label.value(), width / 2, height / 2)
}
Setting other fields
Inside a .changed() function, call .value(newValue) on another field to update it. Here's an example of using this technique to implement presets:
let preset
let size
let color
function setup() {
createCanvas(windowWidth, windowHeight)
preset = createSelect()
preset.option('Small and pink', 'small')
preset.option('Big and blue', 'big')
size = createSlider(10, 200, 50)
color = createColorPicker('#ff6ec4')
preset.changed(() => {
if (preset.value() === 'big') {
size.value(150)
color.value('#4c6ef5')
} else {
size.value(50)
color.value('#ff6ec4')
}
})
}
function draw() {
clear()
noStroke()
fill(color.value())
circle(width / 2, height / 2, size.value())
}
Colors can be set with any CSS color, like '#4c6ef5', 'rebeccapurple' or 'rgb(76, 110, 245)'. The user can still change the other fields afterwards, and picking the preset that is already selected sets them all again.
Showing and hiding fields
Call .show() or .hide() on a field to show or hide it in the sidebar. Consider using this to only show the fields relevant to the current context, e.g. only showing sliders when a "custom" preset is used, to keep the user interface from getting cluttered:
let style
let size
let color
function setup() {
createCanvas(windowWidth, windowHeight)
style = createSelect()
style.option('Simple', 'simple')
style.option('Custom', 'custom')
size = createSlider(10, 200, 100)
color = createColorPicker('#ff6ec4')
style.changed(() => {
if (style.value() === 'custom') {
size.show()
color.show()
} else {
size.hide()
color.hide()
}
})
}
function draw() {
clear()
noStroke()
fill(color.value())
circle(width / 2, height / 2, size.value())
}
Further reading
- The Drop Shadow example, which uses a preset select to set a group of fields and only shows them for a "custom" preset.