The Great Slidini

Slidini

nil

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

Reference