Wasteland Wasteland - 2 months ago 7
HTML Question

JS - combine values from two functions

How do I combine outputs of the two functions to do some operations on the two values?

<div class="grid">
<h2>Adjust the level</h2>
<input
type="range"
name="points"
min="0"
max="10"
step="1"
onChange="xLevel(this.value)">
<input
type="range"
name="points"
min="0"
max="10"
step="1"
onChange="yLevel(this.value)">
<div id="output">
<p id="x"></p>
<p id="y"></p>
</div>
</div>


And the JS is:

var output = document.getElementById("output");

var xout = document.getElementById("x");

var yout = document.getElementById("y");

function xLevel(newVal) {
xout.innerHTML = newVal;
}
function yLevel(newVal) {
yout.innerHTML = newVal;
}


So how do I combine the two values, x and y, to eg. multiply them and display them in yet another div?

Thanks

Answer

Store the new values in their own variables in the top-level scope, and then manipulate them in a separate function.

var output = document.getElementById("output");

var xout = document.getElementById("x");

var yout = document.getElementById("y");

var multout = document.getElementById('mult');

var xval;
var yval;

function xLevel(newVal) {
  xout.innerHTML = newVal;
  xval = parseInt(newVal, 10); // casts it to a number
  updateMultiplier();
}
function yLevel(newVal) {
  yout.innerHTML = newVal;
  yval = parseInt(newVal, 10); // casts it to a number
  updateMultiplier();
}
function updateMultiplier() {
  multout.innerHTML = yval * xval;
}

and then for your markup:

<div class="grid">
  <h2>Adjust the level</h2>
 <input 
        type="range" 
        name="points" 
        min="0" 
        max="10"
        step="1"
     onChange="xLevel(this.value)">
  <input 
        type="range" 
        name="points" 
        min="0" 
        max="10"
        step="1"
     onChange="yLevel(this.value)">
  <div id="output">
    <p id="x"></p>
    <p id="y"></p>
    <p id="mult"></p>
  </div>
</div>