JSFiddle - React, Tailwind, and code Playground
HTML
<h1 id="click-count">0</h1>
<h1 id="did-drag">false</h1>
<div>1. Click on a black dot and watch the counter increment.</div>
<div>2. Drag a dot, being sure that mouseup happens outside the dot. Click a dot, and watch the counter increment.</div>
<div>3. Drag a dot, being sure that mouseup happens directly above the dot. Click a dot. The counter should not increment. Click again. The counter will increment this time.</div>
<svg id="test" width="500" height="500"></svg>
CSS
h1 {
font-size:3em;
}
circle {
fill : #000;
stroke : #000;
cursor: pointer;
}
JavaScript
var data, click_count,did_drag;
data = [
{x : 100, y : 150},
{x : 200, y : 250}
];
click_count = d3.select('#click-count');
did_drag = d3.select('#did-drag');
function eventFire(el, etype){
if (el.fireEvent) {
(el.fireEvent('on' + etype));
} else {
var evObj = document.createEvent('Events');
evObj.initEvent(etype, true, false);
el.dispatchEvent(evObj);
}
}
function draw() {
var drag_behavior,dragged = false;
// clear all circles from the svg element
d3.select('#test').selectAll('circle')
.remove();
drag_behavior = d3.behavior.drag()
.origin(Object)
.on("drag", function(d) {
// indicate that dragging has occurred
dragged = true;
// update the data
d.x = d3.event.x;
// update the display
d3.select(this).attr('cx',d.x);
}).on('dragend',function() {
// data has been updated. redraw.
if(dragged) { draw(); }
eventFire(document,'click');
});
d3.select('#test').selectAll('circle')
.data(data)
.enter()
.append('circle')
.attr('cx',function(d) { return d.x; })
.attr('cy',function(d) { return d.y; })
.attr('r',20)
.on('click',function() {
did_drag.text(dragged.toString());
if(!dragged) {
// increment the click counter
click_count.text(parseInt(click_count.text()) + 1);
}
}).call(drag_behavior);
}
draw();