How to use the HTML5 range input type

Before the introduction of HTML5, thinking about having a range slider on a webpage was equivalent of a crime. You needed a bunch of custom javascript code and still it didn’t work well on all devices.

However, HTML5 brought with it numerous new attributes and features that added the flavor that HTML missed for ages.
Not many would have expected something like the range element to make its entrance with HTML5, but once it did, hardly any have raised any concerns with its working. Creating anything close to the sliding range element takes tons of lines of coding in JavaScript, but the same can be achieved with just a single element in HTML5. How often do you hear that something could be done better in HTML than JavaScript?

As the name suggests, the most common use of the slider input is when we know the lowest and the highest inputs that can be given as a response. For instance, if we are developing a website that only permits users in the age group 18-40. We can have the birth year as a sliding input range with the lowest value being 1986 and the highest being 1998. The slider input is a highly intuitive user interface that projects itself as an alternative to a plain textbox input or a drop-down with fixed values.

The range input is best when you have calculations associated with it. The flexibility of sliding the controls and seeing the result ‘live’ is unmatchable.

How to create input sliding range element in HTML?

Here is the sample code for creating the input range element:

Here are the key attributes:

  • min (The lowest accepted value in the range)
  • max (The highest accepted value in the range)
  • step (The increment/decrement step value default is 1)
  • value (The starting or default value of the slider)

Displaying the current value

The default range element will only display the current position of the slider and the user has to guess the exact value. So in order to avoid the guesswork, you have to use one of the alternatives to display the current value. Here is a mostly HTML solution. (it uses Javascript in the attribute though)

22934

A jQuery Solution to Display values for all range input elements

A more reusable solution would be to create a jquery snippet that handles the change event for all range input elements. Here is the code:

22934

Negative & decimal values in the range input

Yes, you can have negative and decimal values in the range input see below for some examples:

22934

Comments on this entry are closed.