I am trying to draw a UI in d3js where I have a top panel and I should be able drag
and drop
elements to a group and copy them. I have achieved that goal, but there is a bug in my code. What I actually want to do is, drag the circle
and copy it. But when I click the circle
in the top panel it automatically triggers the drag event and copy it self. How can I stop this behaviour?
<svg height="600" width="600" style="background: black">
<g>
<rect x="0" y="0" , width="600" height="40" style="fill:gold;"></rect>
<circle id='drag' cx="15" cy="20" init-cx="15" init-cy="20" r="10"
style="stroke: white; stroke-width: 2px; fill:blue"/>
</g>
<g id="playground">
<g>
<circle id='top' cx="180" cy="120" r="30" style="stroke: white; stroke-width: 2px; fill:white"/>
</g>
<g>
<circle id='top' cx="200" cy="220" r="30" style="stroke: white; stroke-width: 2px; fill:white"/>
</g>
<g>
<circle id='top' cx="320" cy="150" r="50" style="stroke: white; stroke-width: 2px; fill:white"/>
</g>
</g>
</svg>
<script>
$(document).ready(function () {
var move = d3.behavior.drag()
.on('drag', function () {
console.log('dragging');
var curr = d3.select(this)
.attr({
cx: d3.mouse(this)[0],
cy: d3.mouse(this)[1]
})
})
.on('dragend', function () {
var curr = d3.select(this);
d3.select('#playground')
.append('circle')
.attr({
cx : curr.attr('cx'),
cy : curr.attr('cy'),
r : curr.attr('r')
})
.style({
fill : 'white',
stroke : 'red',
'stroke-width' : '2px'
})
;
curr.attr({
cx : curr.attr('init-cx'),
cy : curr.attr('init-cx')
});
})
;
d3.select('#drag').call(move);
});
</script>
here is the fiddle of my work. https://jsfiddle.net/fawzan/my2g724L/