D3 slider
HTML
<h2>Slider with slide event: <span id="slider3text">0</span></h2>
<div id="slider3"></div>
CSS
body {
font-family: Verdana,Arial,sans-serif;
}
h2 {
font-size: 1.2em;
margin: 60px 0 5px 0;
}
.wrapper div {
margin: 35px 0;
}
.wrapper {
width: 800px;
margin-left: auto;
margin-right: auto;
}
#slider7 {
height: 250px;
}
.d3-slider {
position: relative;
font-family: Verdana,Arial,sans-serif;
font-size: 1.1em;
border: 1px solid #aaaaaa;
z-index: 2;
}
.d3-slider-horizontal {
height: .8em;
}
.d3-slider-vertical {
width: .8em;
height: 100px;
}
.d3-slider-handle {
position: absolute;
width: 1.2em;
height: 1.2em;
border: 1px solid #d3d3d3;
border-radius: 4px;
background: #eee;
background: linear-gradient(to bottom, #eee 0%, #ddd 100%);
z-index: 3;
}
.d3-slider-handle:hover {
border: 1px solid #999999;
}
.d3-slider-horizontal .d3-slider-handle {
top: -.3em;
margin-left: -.6em;
}
.d3-slider-axis {
position: relative;
z-index: 1;
}
.d3-slider-axis-bottom {
top: .8em;
}
.d3-slider-axis-right {
left: .8em;
}
.d3-slider-axis path {
stroke-width: 0;
fill: none;
}
.d3-slider-axis line {
fill: none;
stroke: #aaa;
shape-rendering: crispEdges;
}
.d3-slider-axis text {
font-size: 11px;
}
.d3-slider-vertical .d3-slider-handle {
left: -.25em;
margin-left: 0;
margin-bottom: -.6em;
}
JavaScript
/*
D3.js Slider
Inspired by jQuery UI Slider
Copyright (c) 2013, Bjorn Sandvik - http://blog.thematicmapping.org
BSD license: http://opensource.org/licenses/BSD-3-Clause
*/
d3.slider = function module() {
"use strict";
// Public variables width default settings
var min = 0,
max = 100,
step = 1,
animate = true,
orientation = "horizontal",
axis = false,
margin = 50,
value,
scale;
// Private variables
var axisScale,
dispatch = d3.dispatch("slide"),
formatPercent = d3.format(".2%"),
tickFormat = d3.format(".0"),
sliderLength;
function slider(selection) {
selection.each(function() {
// Create scale if not defined by user
if (!scale) {
scale = d3.scale.linear().domain([min, max]);
}
// Start value
value = value || scale.domain()[0];
// DIV container
var div = d3.select(this).classed("d3-slider d3-slider-" + orientation, true);
var drag = d3.behavior.drag();
// Slider handle
var handle = div.append("a")
.classed("d3-slider-handle", true)
.attr("xlink:href", "#")
.on("click", stopPropagation)
.call(drag);
// Horizontal slider
if (orientation === "horizontal") {
div.on("click", onClickHorizontal);
drag.on("drag", onDragHorizontal);
handle.style("left", formatPercent(scale(value)));
sliderLength = parseInt(div.style("width"), 10);
} else { // Vertical
div.on("click", onClickVertical);
drag.on("drag", onDragVertical);
handle.style("bottom", formatPercent(scale(value)));
sliderLength = parseInt(div.style("height"), 10);
}
if (axis) {
createAxis(div);
}
function createAxis(dom) {
// Create axis if not defined by user
if (typeof axis === "boolean") {
axis = d3.svg.axis()
...