D3.js drag slider

by Michael Keller

CSS

body{
    margin: 75px;
}
.slider-group{
    position: relative;
}
.slider{
    background-color: #c0c0c0;
    height: 5px;
}
.slider-handle{
    border-radius: 50%;
    background-color: #2394F5;
    position: absolute;
}

JavaScript

var drag = d3.behavior.drag()
.origin(function(d){ return d;})
            .on("drag", dragMove)
            .on('dragend', dragEnd);

var drag_width = '260px',
    slider_height = 5;

var dragScale = d3.scale.pow()
        .exponent(5)
        .domain([0,parseInt(drag_width)])
        .range([1,50000000]);

var siNotation = d3.format('.2s');

var canvas = d3.select('body')
                .append('div')
                .attr('id','canvas')
                .style('height', '200px')
                .style('width', '300px');

var g = canvas.selectAll('.slider-group')
.data([{x: 100, y: circle_width/-2}])
            .enter()
                .append('div')
                .classed('slider-group', true)
                .style("height", '200px')
                .style("width", drag_width);

var rect = g
                .append('div')
                .classed('slider', true)
                .style('height', slider_height+'px')
                .style("width", drag_width);

var circle_width = 25;
g.append("div")
    .classed('slider-handle', true)
    .style("left", function(d) { 
        return d.x+'px';
    })
    .style('transform', 'translate('+(circle_width/-2)+'px,'+(circle_width/-2 - slider_height/2)+'px)')
    .style('width', circle_width+'px')
    .style('height', circle_width+'px')
    .call(drag);

function dragMove(d) {
    var max_width = parseInt(drag_width);
    var cx = Math.max(0, Math.min(max_width, d3.event.x))
    d3.select(this)
        .style("opacity", 0.6)
        .style("left", function(d){
            d.x = cx;
            return cx+'px'
        });
    
   console.log(cx, siNotation(dragScale(cx)));
}

function dragEnd() {
    d3.select(this)
        .style('opacity', 1)
}