Created
November 2, 2015 21:54
-
-
Save jcardente/bca4095be15dd0264684 to your computer and use it in GitHub Desktop.
Slider control in D3js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Simple slider control in D3js. | |
// Based on Mike Bostock's example | |
// http://bl.ocks.org/mbostock/6452972 | |
// Slider in D3 | |
function makeSlider(label, x,y,scale,cb) { | |
var brush = d3.svg.brush() | |
.x(scale) | |
.extent([0,0]) | |
.on("brush", brushed); | |
var label = svg.append("text") | |
.attr("x", x-5) | |
.attr("y", y) | |
.text(label); | |
var brushg = svg.append("g") | |
.attr("transform", "translate(" + x + "," + (y+10) + ")"); | |
brushg.append("g") | |
.attr("class", "x axis") | |
.call(d3.svg.axis() | |
.scale(scale) | |
.ticks(5) | |
.tickSize(1) | |
.tickFormat(function(d) {return Math.floor(d*100) + "%";}) | |
.tickPadding(10) | |
.orient("bottom")); | |
var slider = brushg.append("g") | |
.attr("class", "slider") | |
.call(brush); | |
var handle = slider.append("circle") | |
.attr("r", 5) | |
.attr("cx", 0) | |
.attr("cy", 0) | |
.attr("stroke", "#000") | |
.attr("fill", "#DDD"); | |
slider.call(brush); | |
function brushed() { | |
var value = brush.extent()[0]; | |
if (d3.event.sourceEvent) { // not a programmatic event | |
value = scale.invert(d3.mouse(this)[0]); | |
brush.extent([value, value]); | |
} | |
handle.attr("cx", scale(value)); | |
cb(value); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment