Table of Contents

2.3.4. Sliders

Purpose

Sliders are form fields that let the user select a specific value within a range of predefined values. Normally, they are shown as a slider that can be moved along an axis, between the minimal value and a second value which is the maximum value.

Sometimes, you can move the slider anywhere on the scale; other times you have to choose one of the predefined values on the scale.

They are said to be “simulated” when they do not use the default form elements included in HTML, namely the <input type=“range” /> fields. They are often used because they are more attractive.

Basic HTML code

The basic HTML code uses a standard HTML5 slider:

<form action="index.html" method="post">
    <label for="sleep-quality" id="sleep-quality-label">
        Are you satisfied with the quality of your sleep?
        (whole number, from 1 for “Very dissatisfied” to 5 for “Very satisfied")
    </label>
    <input type="range" id="sleep-quality" name="sleep-quality" step="1" value="3" min="1" max="5" />
 
    <input type="submit" value="Submit information" />
</form>

Warning It is very important to indicate the format of data required from the user.

If HTML5 is not supported by the user’s browser, and if JavaScript is not activated, a text field will be displayed by default. Without instructions, the user will not know the range of authorized values.

Without JavaScript, a standard form is shown to the user.

Behaviour with JavaScript

With JavaScript, the behaviour of simulated sliders must the same as those of standard sliders.

Essentially, the method consists of the following steps:

  1. The standard slider is hidden in JavaScript.
  2. An empty container is created in the DOM, in the place of the initial slider. It will contain the other slider elements. When it has been styled with CSS, it will symbolize the axis of the slider.
  3. A second empty element is created in the DOM as a child of the previous element. When styled in CSS, it will be used as the slider.
  4. JavaScript is then used to add ARIA roles and manage the behaviour of the simulated slider.

Going into more detail, the scripts must handle the following points:

The resulting code in JavaScript is as follows:

<form action="index.html" method="post">
    <label for="Sleep-quality" id="sleep-quality-label">
        Are you satisfied with the quality of your sleep?
        (Whole number, from 1 for “Very dissatisfied” to 5 for “Very satisfied")
    </label>
    <input style="display: none;" type="range" id="sleep-quality" name="sleep-quality" step="1" value="3" min="1" max="5" />
    <div id="slider-container">
        <span id="slider-cursor" role="slider" tabindex="0" aria-labelledby="sleep-quality-label" aria-valuemin="1" aria-valuemax="5" aria-valuenow="5" aria-valuetext="Very satisfied"></span>
    </div>
 
    <input type="submit" value="Submit information" />
</form>

Demonstration