In this post, I'm going to walk through how to update a Javascript NodeList based on the input values of an HTML range. Every time a user to our website moves the input slider, we will take the value of the slider and multiply it by an array of constants to produce a new value. Finally, we will output this new value to the page.
Let's start by defining our array of constants.
<script> const values = [400, 9000, 30, 250, 1]; </script>
Next, we'll use the Javascript method getElementsByClassName to retrieve our HTML elements which will be updated later on. While we're at it, we should instantiate a blank array that we can fill with values before printing them to the page.
var widgets = document.getElementsByClassName('widget'); var newValues = [];
Before writing any logic, let's attach an event listener to a range input. This is a very simple HTML slider with 5 possible selected values because it steps at an interval of 25. (0, 25, 50, 75, and 100). Our code will interpret these as (0, 1, 2, 3, and 4).
<input type="range" value="0" step ="25" oninput="updateValue(this.value)">
Now comes the fun part: let's write a Javascript function that does three things:
- Iterate through the constants defined above, passing through both the individual value and an iterator.
- Multiply the constant by the variable slider, passed through from the event listener. Store this product in the previously empty newValues array.
- Use innerHTML to append these newValues to the classes we want to update in the HTML, defined above by the document selector.
function updateValue(slider) { values.forEach(function(value, i) { newValues.push(value * slider); widgets[i].innerHTML = newValues[i]; }); }
Now when the slider is pushed to 2, slider gets passed through as an argument and multiplied by each of the values. The result is this array:
const values = [800, 18000, 60, 500, 2];
This array then gets added to each of the 5 widget elements. Just for the record, this is the HTML structure of my widgets. The zero gets updated with new values from the function.
<div class="widget"> 0 </div>
However, at this point the slider only works for the first value called. Why is that? Well, the second time the function updateValue gets called newValues is no longer blank, so the second value gets appended to the end!
We can easily fix this by clearing newValues after the innerHTML call but before the function is closed. Here is the complete final product:
<script> const values = [400, 9000, 30, 250 ,1]; var widgets = document.getElementsByClassName('widget'); var newValues = []; function updateValue(slider) { values.forEach(function(value, i) { newValues.push(value * slider); widgets[i].innerHTML = newValues[i]; }); // clear new value newValues = []; } </script>