Skip to content

Instantly share code, notes, and snippets.

@SabinT
Last active May 19, 2022 05:22
Show Gist options
  • Save SabinT/85417723546c9bff50c4f336f0f11fd2 to your computer and use it in GitHub Desktop.
Save SabinT/85417723546c9bff50c4f336f0f11fd2 to your computer and use it in GitHub Desktop.
p5js createSlider with label and values
/**
* Example:
* let param1 = 5;
* createSlider(0, 10, param1, 0.01, "Param 1", (val) => { param1 = val; });
*/
export function createSlider (min, max, value, step, text, valueChangeHandler) {
const container = document.createElement('div');
const label = document.createElement('div');
const elt = document.createElement('input');
label.setAttribute('style', "background: #214288; color: white; font-family: monospace; font-size: large");
container.setAttribute('style', "display: flex;");
const changeHandler = () => {
if (valueChangeHandler) { valueChangeHandler(Number(elt.value)) }
label.textContent = `${text} [${min}, ${max}] = ${elt.value}`;
};
elt.addEventListener('input', changeHandler);
elt.type = 'range';
elt.min = min;
elt.max = max;
if (step === 0) {
elt.step = 0.000000000000000001; // smallest valid step
} else if (step) {
elt.step = step;
}
if (typeof value === 'number') elt.value = value;
changeHandler();
container.appendChild(elt);
container.appendChild(label);
document.body.appendChild(container);
return elt;
};
@SabinT
Copy link
Author

SabinT commented May 18, 2022

This will create a slider that looks like this:
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment