D3.slider

A slider control using d3.js

Download .zip Download .tar.gz View on GitHub

d3.slider is a configurable slider control built with d3.js

Usage

Code

In the head section of your html page, include the d3.slider.js and d3.slider.css files, and also include the d3 library

<link rel="stylesheet" type="text/css" href="stylesheets/d3.slider.css" media="screen" />
<script src="javascripts/d3.v3.min.js"></script>
<script src="javascripts/d3.slider.js"></script>

In your html, create a div with a specified width. This will be the container for the slider.

<div id="slider"></div>

In your javascript code, create and initialize the slider with the required options, and call the slider function on the div like this

// Initialize slider
var slider = d3.slider().min(0).max(10).ticks(10).showRange(true).value(6);
// Render the slider in the div
d3.select('#slider').call(slider);

Output

Examples

The slider can be customized with various options. These are documented below.

Minimum and maximum values

The minimum and maximum values for the slider have to be specified. They can be specified as follows

var slider = d3.slider().min(0).max(10);

This will create a slider for the specified range, without any tick marks, as shown below

Specifying ticks

Ticks can be specified in multiple ways

Specifying number of ticks

Slider with number of ticks specified. Tick values are calculated by d3's axis tick functions

var slider = d3.slider().min(0).max(10).ticks(10);
Tick values as arguments

Tick values can be specified as an array of values between the minimum and maximum values, and do not necessarily have to be evenly spaced.

var slider = d3.slider().min(0).max(10).tickValues([1,3,5,7,10]);

Step increments

Slider movement can be continuous or in steps

Slider with step increments. Step values are specified as an array. If tickValues are also specified, the tick values array must be a subset of the step values.

var slider = d3.slider().min(0).max(20).tickValues([0,5,10,15,20]).stepValues([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19.20]);

Custom tick format

The text displayed for ticks can be customized by passing in a function for tickFormat

// tick formatter
var formatter = d3.format(",.2f");
var tickFormatter = function(d) {
return formatter(d) + " GB";
}
var slider = d3.slider().min(0).max(50).ticks(10).showRange(true)
.tickFormat(tickFormatter);

Current value range shaded

The range from minimum to the current slider value can be displayed shaded as shown below.

var slider = d3.slider().min(0).max(10).ticks(10).showRange(true).value(4);

Initial value

The initial value of the slider can be set as shown below

var slider = d3.slider().min(0).max(10).ticks(10).showRange(true).value(6);

Destroying the slider

The slider can be destroyed by calling the destroy method. This will remove the contents of the div on which the slider was called. It will not remove the div itself.

slider.destroy()