document.addEventListener("DOMContentLoaded",function(){ let ranges = [ new RangePill("#range1","orange"), new RangePill("#range2","yellow"), new RangePill("#range3","blue"), new RangePill("#range4","white","orange"), new RangePill("#range5","white","yellow"), new RangePill("#range6","white","blue"), new RangePill("#range7","orange","yellow"), new RangePill("#range8","blue","orange"), new RangePill("#range9","yellow","blue"), new RangePill("#range10","yellow","orange"), new RangePill("#range11","orange","blue"), new RangePill("#range12","blue","yellow") ]; }); class RangePill { constructor(qs,thumbColor = "orange",trackColor = "white") { this.el = document.querySelector(qs); this.fill = null; this.value = null; if (this.el) { this.buildSlider(thumbColor,trackColor); this.el.addEventListener("input",this.changeValue.bind(this)); } } buildSlider(thumbColor,trackColor) { this.el.className = "range-pill__input"; // create a div to contain the let rangeWrap = document.createElement("span"); rangeWrap.className = "range-pill"; // thumb and track colors if (thumbColor) rangeWrap.classList.add(`range-pill--${thumbColor}-thumb`); if (trackColor) rangeWrap.classList.add(`range-pill--${trackColor}-track`); this.el.parentElement.insertBefore(rangeWrap,this.el); // input rangeWrap.appendChild(this.el); // range fill let rangeFill = document.createElement("span"); rangeFill.className = "range-pill__fill"; rangeWrap.appendChild(rangeFill); // range value let rangeValue = document.createElement("span"); rangeValue.className = "range-pill__value"; rangeValue.textContent = this.el.value; rangeWrap.appendChild(rangeValue); // initial value this.fill = rangeFill; this.value = rangeValue; this.changeValue(); } changeValue() { // keep the value within range if (+this.el.value > this.el.max) this.el.value = this.el.max; else if (+this.el.value < this.el.min) this.el.value = this.el.min; // width of fill if (this.fill) { let pct = (this.el.value - this.el.min) / (this.el.max - this.el.min), fillWidth = pct * 100; this.fill.style.width = `${fillWidth}%`; } // value if (this.value) this.value.textContent = this.el.value; } }