Finally, let's have a look at the JavaScript code. It starts by stashing references to the elements it will need to access, using Document.getElementById():
const widthSlider = document.getElementById("widthSlider");
const widthDisplay = document.getElementById("widthDisplay");
const textElement = document.getElementById("hello");
const baseLength = Math.floor(textElement.textLength.baseVal.value);
widthSlider.value = baseLength;
widthSlider.addEventListener(
"input",
(event) => {
textElement.textLength.baseVal.newValueSpecifiedUnits(
SVGLength.SVG_LENGTHTYPE_PX,
widthSlider.valueAsNumber
);
widthDisplay.innerText = widthSlider.value;
},
false
);
widthSlider.dispatchEvent(new Event("input"));
After fetching the element references, an EventListener is established by calling addEventListener() on the slider control, to receive any input events which occur. These events will be sent any time the slider's value changes, even if the user hasn't stopped moving it, so we can responsively adjust the text width.
When an "input" event occurs, we call newValueSpecifiedUnits() to set the value of textLength to the slider's new value, using the SVGLength interface's SVG_LENGTHTYPE_PX unit type to indicate that the value represents pixels. Note that we have to dive into textLength to get its baseVal property; textLength is stored as an SVGLength object, so we can't treat it like a plain number.
After updating the text width, the contents of the widthDisplay box are updated with the new value as well, and we're finished.