jquerycssd3.js

Autoscroll on mousedrag


Created D3 tree. Horizontal scroll bar is not working on drag selection of tree node in Firefox 37. In chrome horizontal scroll is working on drag selection.

<div class="row">
     <div class="tree-container" id="treeId"></div>
</div>

jQuery

$('.tree-container').css('overflow', 'auto');

var nodeEnter = node.enter().append("g").call(dragListener).attr(
            "class", "node").attr("transform", function(d) {
        return "translate(" + source.y0 + "," + source.x0 + ")";
    }).on("mouseenter", nodeMouseEnter).on("mouseleave", nodeMouseLeave)
            .on('click', click).attr('id', function(d) {
                return d.nodeId;
            });

Solution

  • HTML Code is here :

     <div id="outerFrame">
        <div id="innerFrame">
            <svg width="600" height="600">
            </svg>
        </div>
    </div>
    

    CSS:

        #outerFrame{
            width: 300px;
            height: 300px;
            border: 1px solid red;
           overflow: auto;
    }
    
     #innerFrame{
        width: 600px;
        height: 600px;
        background-color: lightgrey;
    }
    
    rect{
        fill: green;
    }
    

    JS code :

    var drag = d3.behavior.drag()
        .on("dragstart", dragstart)
        .on("drag", dragmove)
        .on("dragend", dragend);
    
    function dragstart() {
      d3.select(this).style("border", "1px solid red");
    }
    
    function dragmove(d) {
        var svg = d3.select("svg").node(),
            $parent = $('#outerFrame'),
            w = $parent.width(), h = $parent.height(),
            sL = $parent.scrollLeft(), sT = $parent.scrollTop();
    
        var coordinates = d3.mouse(svg),
            x = coordinates[0],
            y = coordinates[1];
    
        if (x > w + sL) {
            $parent.scrollLeft(x - w);  
        } else if (x < sL) {
            $parent.scrollLeft(x);
        }
    
        if (y > h + sT) {
            $parent.scrollTop(y - h);
        } else if (y < sT) {
            $parent.scrollTop(y);
        }
    
        d3.select(this).attr({
            x: x - 50,
            y: y - 25
        })
    }
    
    function dragend() {
      d3.select(this).style("border", null);
    }
    
    d3.select("svg")
        .append("rect")
        .attr({x: 100, y: 100, width: 100, height: 50})
        .call(drag);