Fawzan
Fawzan

Reputation: 4849

D3js moving nested groups

I am trying to move nested svg group elements within a group. My requirement is to move the large rectangle along with all the elements in it, But I also need to move the individual groups inside the large rectangle to be moved (only inside the large rectangle). I can move the large group but not the groups inside it. Here is the fiddle with my work. Can anyone help me?

<g id="a" transform="translate(0,0)">
    <g>
        <rect x="10" y="10" width="200" height="200" fill="red"></rect>
        <circle r="5" cx="10" cy="105" fill="blue"></circle>
        <circle r="5" cx="210" cy="105" fill="blue"></circle>
    </g>
    <g id="b" class="e" transform="translate(0,0)">
        <rect x="20" y="20" width="50" height="50" fill="black"></rect>
        <circle r="5" cx="20" cy="45" fill="blue"></circle>
        <circle r="5" cx="70" cy="45" fill="blue"></circle>
    </g>
    <g id="c" class="e" transform="translate(0,0)">
        <rect x="90" y="20" width="50" height="50" fill="black"></rect>
        <circle r="5" cx="90" cy="45" fill="blue"></circle>
        <circle r="5" cx="140" cy="45" fill="blue"></circle>
    </g>
</g>

<script>
    d3.select('#a').call(d3.behavior.drag().on('drag', function () {
        d3.select(this).attr('transform', 'translate(' + d3.event.x + ',' + d3.event.y + ')');
//        d3.event.stopPropagation();

    }));

    d3.selectAll('.e').call(d3.behavior.drag().on('drag', function () {
        d3.select(this).attr('transform', 'translate(' + d3.event.x + ',' + d3.event.y + ')');
        d3.event.stopPropagation();
    }));


</script>

Upvotes: 0

Views: 290

Answers (1)

potatopeelings
potatopeelings

Reputation: 41075

You need to do a stopPropagation on the dragstart event of your inner boxes.

d3.selectAll('.e').call(d3.behavior.drag()
     .on('dragstart', function () {
         d3.event.sourceEvent.stopPropagation();
      })
     .on('drag', function () {
     ...

Note - to restrict the drag area for the inner boxes, just limit your translate values to > 0 and the maximum size of the parent box (here's a related question - Explaining Mike Bostock's d3.js dragmove function).

By the way, if you set the origin for the drag, it won't jump (to align the top left corner with the mouse position) when you start to drag.


Fiddle - https://jsfiddle.net/v9487fhh/

Upvotes: 1

Related Questions