Skip to content

Instantly share code, notes, and snippets.

@jcardente
Created November 2, 2015 21:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcardente/bca4095be15dd0264684 to your computer and use it in GitHub Desktop.
Save jcardente/bca4095be15dd0264684 to your computer and use it in GitHub Desktop.
Slider control in D3js
// 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