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.
- Introduction to sliders
- Accessible slider alternative
- Basic requirements for sliders
- Connecting the slider to the form
- Scripting the slider regions (this post)
- 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) { $(this).removeClass('selected'); if (region === index) { $(this).addClass('selected'); } });
The regions now change depending on where the slider is positioned.
Next: Conclusion to sliders
