D3.js drag slider
by Chetan Hanumantha
CSS
rect {
float: left;
border: solid 1px #aaa;
}
JavaScript
var drag = d3.behavior.drag()
.origin(Object)
.on("drag", dragMove)
.on('dragend', dragEnd);
var svg = d3.select('body')
.append('svg')
.attr("height", 200)
.attr("widht", 300);
var g = svg.selectAll('g')
.data([{x: 270, y : 20}])
.enter()
.append('g')
.attr("height", 200)
.attr("widht", 300)
.attr('transform', 'translate(20, 10)');
var rect = g.append('rect')
.attr('y', 17)
.attr("height", 5)
.attr("width", 280)
.attr('fill', '#C0C0C0');
g.append("circle")
.attr("r", 10)
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })
.attr("fill", "#2394F5")
.call(drag);
function dragMove(d) {
d3.select(this)
.attr("opacity", 0.6)
.attr("cx", d.x = Math.max(0, Math.min(280, d3.event.x)))
.attr("cy", d.y = 20);
}
function dragEnd() {
d3.select(this)
.attr('opacity', 1)
}