Programming

Create Sliders with the Range Input in HTML5

How to Create Sliders with the Range Input in HTML5

HTML5 introduces the new range type of input.<input type=”range”>

Most notably, it can receive min, max, step, and value attributes, among others. Though only Opera seems to support this type of input right now fully, it’ll be fantastic when we can actually use this!
For a quick demonstration, let’s build a gauge that will allow users to decide how awesome “Total Recall” is. We won’t build a real-world polling solution, but we’ll review how it could be done quite easily.

Step 1: Mark-up

First, we create our mark-up.

Total Recall Awesomness Gauge

 

<form method=”post”>
<h1> Total Recall Awesomness Gauge </h1>
<input type=”range” name=”range” min=”0″ max=”10″ step=”1″ value=””>
<output name=”result”> </output>
</form>
Unstyled range input
Notice that, in addition to setting min and max values, we can always specify what the step for each transition will be. If the step is set to 1, there will then be 10 values to choose. We also take advantage of the new output element that we learned about in the previous tip.

Recommended Reading:ADD OR REMOVE HTML CLASSES IN JQUERY

Step 2: CSS

Next, we’ll style it just a bit. We’ll also utilize :before and :after to inform the user what our specified min and max values are. Thanks so much to Remy and Bruce for teaching me this trick, via “Introducing HTML5.”
view plaincopy to clipboardprint?

Recommended Reading:CREATING MODAL WINDOW OR HIGHSLIDE WINDOW USING HTML5
Above, we create content before and after the range input, and make their values equal to the min and max values, respectively.
Styled Range

Step 3: The JavaScript

Lastly, we:
Determine if the current browser knows what the range input is. If not, we alert the user that the demo won’t work.
Update the output element dynamically, as the user moves the slider.
Listen for when the user mouses off the slider, grab the value, and save it to local storage.
Then, the next time the user refreshes the page, the range and output will automatically be set to what they last selected.