Scripting the slider regions

Now that we have connected the slider to the form, we can provide some added enhancement by showing in bold the appropriate region description underneath the slider.

This post is part of a series that guides you through creating robust sliders for your forms.

  1. Introduction to sliders
  2. Accessible slider alternative
  3. Basic requirements for sliders
  4. Connecting the slider to the form
  5. Scripting the slider regions (this post)
  6. Conclusion to sliders

To set the active slider region, we will walk through each region and set one of them to have a class name called selected. While we’re walking through each of them, we can handle situations where the region changes to a different description, by removing the selected class name from the regions beforehand.

To tell if a region is the right one or not, we can convert the slider value to a number for each of the regions, where we use Math.floor to round down the slider value after division.

var $ul = $(ui.handle).parent().next('ul'),
    $regions = $('li', $ul),
    region = Math.floor(ui.value * $regions.length / 100);

This works well with numbers from 0 to 99, but the slider ends at 100 so we also need to ensure that the region value doesn’t fall outside the number of regions.

if (region > $regions.length) {
    region = $regions.length;

Even though can easily specify the min and max numbers for the slider, ending the slider at 100 provides the user with a more complete experience.

Now that we have the regions, and we know which one we want to be selected, we can walk through each region and the set the class name as is appropriate for each one.

$regions.each(function (index) {
    if (region === index) {

The regions now change depending on where the slider is positioned.

Slider form in use

Next: Conclusion to sliders


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: