In this post we’ll look at updating an output value using input range scrollbars using JavaScript.

We will calculate the area of a cuboid based on the length, width and height of the cuboid:

$ Area = length \times width \times height $

See the result in the CodePen example below:

See the Pen VxqLBe by Ben (@benalexkeen) on CodePen.0

We’ll start with our HTML inputs and output.

For each input we have:

  • The name of the input e.g. Length.
  • The value (e.g. lengthValue) defaulted to zero.
  • A slider (e.g. lengthSlider), with a range between 0 and 100, and a step of 1, defaulted to zero.
    • When we make a change to the slider, a JavaScript function is called with the updated value (e.g. oninput="lengthSliderChange(this.value)")

<p>Length: <output id="lengthValue">0</output>
<br/>
<input id="lengthSlider" type="range" min="0" max="100" step="1" value="0" oninput="lengthSliderChange(this.value)" style="width: 200px"></p>

<p>Width: <output id="widthValue">0</output>
<br/>
<input id="widthSlider" type="range" min="0" max="100" step="1" value="0" oninput="widthSliderChange(this.value)" style="width: 200px"></p> <p>

Height: <output id="heightValue">0</output>
<br/>
<input id="heightSlider" type="range" min="0" max="100" step="1" value="0" oninput="heightSliderChange(this.value)" style="width: 200px"></p> <p>

Area: <output id="areaValue">0</output><br/></p>

Each time we update any of the slider values, we want to update the area, so we define a function to update the area based on the input slider values:


function updateAreaValue() {
  var length = document.getElementById('lengthSlider').value;
  var width = document.getElementById('widthSlider').value;
  var height = document.getElementById('heightSlider').value;
  var area = length * width * height;
  document.getElementById('areaValue').innerHTML = area;
}

Now we define our functions to be called whenever any of the slider values change. When a slider value changes, we want to change its associated value and we want to change the value of the area.


function lengthSliderChange(val) {
         document.getElementById('lengthValue').innerHTML = val;
         updateAreaValue();
      }

function widthSliderChange(val) {
         document.getElementById('widthValue').innerHTML = val;
         updateAreaValue();
      }

function heightSliderChange(val) {
         document.getElementById('heightValue').innerHTML = val;
         updateAreaValue();
      }