The Great Slidini
Table of Contents
Slidini
The Class Declaration
The Slidini class is going to create two HTML elements - a Slider and a label (what I call a caption) for the slider.
class Slidini {
_slider = null;
_caption = null;
The Constructor
Feature: A Slidini class to hold a slider and its caption.
constructor(slider_settings, caption_settings, p5) {
this.slider_settings = slider_settings;
this.caption_settings = caption_settings;
this.p5 = p5;
} // constructor
The slider_settings
and caption_settings
should be instances of the SliderSettings
and CaptionSettings
classes (see the Slider and Caption Settings post) and the p5
object should be a p5.js instance.
The Slider
This creates the slider and the caption. I decided to muddy them together like this in order to create the callback to update the caption whenever the slider is updated, and to add the initial caption once the slider is created.
get slider() {
if (this._slider === null) {
// create the slider
this._slider = this.p5.createSlider(
this.slider_settings.min,
this.slider_settings.max,
this.slider_settings.default_value,
this.slider_settings.step_size,
);
// attach it to the div tag
this._slider.parent(this.slider_settings.slider_div);
// set the callback to change label on update
this._slider.input(() => this.update_caption());
// add the label to the slider
this.update_caption();
}
return this._slider;
}
The Caption
This is the caption for the slider. It expects there to be a div
that it can stick the caption into.
get caption() {
if (this._caption === null) {
this._caption = this.p5.select(
this.caption_settings.div_selector);
}
return this._caption;
}
The Caption Updater
This sets the caption to the current value of the slider. It's used both to initialize the caption and as a callback to update the caption whenever the slider's value changes.
update_caption() {
this.caption.html(
`${this.caption_settings.label}: ` +
`${this.slider.value().toFixed(this.caption_settings.precision)}`);
} // update_caption
Links
Related Posts
Reference
- p5.js reference | createSlider() [Internet]. [cited 2023 Apr 25]. Available from: https://p5js.org/reference/#/p5/createSlider
- p5.js reference | p5.Element [Internet]. [cited 2023 Sep 14]. Available from: https://p5js.org/reference/#/p5.Element
- p5.js reference | html() [Internet]. [cited 2023 Sep 14]. Available from: https://p5js.org/reference/#/p5.Element/html
- p5.js reference | parent() [Internet]. [cited 2023 Sep 14]. Available from: https://p5js.org/reference/#/p5.Element/parent
- p5.js reference | select() [Internet]. [cited 2023 Sep 14]. Available from: https://p5js.org/reference/#/p5/select