Displaying an HTML slider’s value

HTML5 sliders, or <input type=”range”> are a cool new input type, but he problem is, the user has no indication of which value they have selected. Luckily, this is easy to fix

Firstly you can create your slider and give it a class name, and a unique id. For example:

<input type="range" class="slider" id="slider1" /><br/>
<input type="range" class="slider" value="20" id="slider2" />

Then we will see where its value will go. You can create a span whose id is the same as the slider + ‘_value’ for example. This will help us be able to access the elements with javascript later:

<input type="range" class="slider" id="slider1" />
<span id="slider1_value"></span><br/>
<input type="range" class="slider" value="20" id="slider2" />
<span id="slider2_value"></span>

Now all we have to do is loop through our sliders, and update the innerHTML of the value span as they change:

<script>
    var sliders = document.getElementsByClassName('slider');
    // class='slider' elements :p
    var len     = sliders.length;

    for ( var i = 0; i < len; i++ ) {
        var slider = sliders[i];

        slider.addEventListener('change', function() {
            updateValue(this);
        });

        updateValue(slider);
    }

    function updateValue(slider) {
        var id        = slider.id;

        if (!id) {
            return;
        }

        var val       = document.getElementById(id + '_value');
        // Find the span whose id is the id of the slider + _value..
        
        if (val) {
            val.innerHTML = slider.value; // And update it!
        }
    }
</script>

Now your sliders should have values next to them (or wherever you place your _value element) that auto-update as you change them =)

Example!



That's all for now! See you next time =)

Leave a Comment

Your email address will not be published. Required fields are marked *