Skip to content

Instantly share code, notes, and snippets.

@theicfire
Last active December 23, 2015 03:28
Show Gist options
  • Save theicfire/6573314 to your computer and use it in GitHub Desktop.
Save theicfire/6573314 to your computer and use it in GitHub Desktop.
Resizable line with handles | SVG, d3.js, Javascript
<!DOCTYPE html>
<meta charset="utf-8">
<style>
svg {
float: left;
}
line {
shape-rendering: crispEdges;
stroke-width: 1px;
fill: none;
stroke: #000;
}
</style>
<script src="http://mbostock.github.com/d3/d3.js?2.7.1"></script>
<body>
<script>
var width = 300,
height = 100,
handle_height = 10;
var max_x = 200;
var min_x = 0;
var grab_width = 30;
var svg = d3.select("body").append("svg")
.attr("width", width+10)
.attr("height", height);
var axis = svg.append('g')
.attr('class', 'interval-range')
.attr('transform', 'translate(5, 10)');
axis.append('line')
.attr('class', 'interval-range-line')
.attr('y2', 0)
.attr('x2', max_x);
make_handle('right');
make_handle('left');
function make_handle (direction) {
var set_handle_position = function (handle, direction) {
handle.attr('y1', -handle_height).attr('y2', handle_height + 1);
if (direction === 'right') {
handle.attr('x1', max_x).attr('x2', max_x)
}
}
var good_x = function(x) {
return Math.max(Math.min(max_x, x), min_x);
}
var drag_handle = function (direction) {
return d3.behavior.drag()
.on('drag', function (d) {
var x = good_x(d3.event.x);
d3.select('.interval-range-line')
.attr(direction === 'right' ? 'x2' : 'x1', x);
d3.selectAll('.interval-' + direction + '-handle line')
.attr('x1', x)
.attr('x2', x);
});
}
var handle = axis.append('g')
.attr('class', 'interval-' + direction + '-handle')
.call(drag_handle(direction));
// a hidden but thick line to make clicking easier
var hidden_handle = handle.append('line')
.style('stroke-width', grab_width)
.style('opacity', 0);
set_handle_position(hidden_handle, direction);
var visible_handle = handle.append('line');
set_handle_position(visible_handle, direction);
}
</script>
@theicfire
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment