Reputation: 2388
I'm creating a d3 force directed graph. My requirement is to have both single click and double click on a node.
On single click , i need to perform different tasks and on double click , some other task.
This is what my code looks like:
var node = svg.append("g")
.attr("class", "nodes")
.selectAll("circle")
.data(graph.nodes)
.enter().append("circle")
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })
.attr("r", 5)
.on("click",function(d){ alert("node was single clicked"); })
.on("dblclick",function(d){ alert("node was double clicked"); })
The problem here is , even though I double click on the node, single click function is called.
How do i prevent click
function to be called when I double click on the node.
In other words, when node is single clicked, then click
function has to be called, when double clicked, then dblclick
function has to be called.
Many thanks to anyone who can help me solve this problem.
Upvotes: 3
Views: 4078
Reputation: 8509
You can distinguish between single click and double click using setTimeout
, check the demo:
var timeout = null;
d3.select('rect').on("click", function(d) {
clearTimeout(timeout);
timeout = setTimeout(function() {
console.clear();
console.log("node was single clicked", new Date());
}, 300)
})
.on("dblclick", function(d) {
clearTimeout(timeout);
console.clear();
console.log("node was double clicked", new Date());
});
rect {
fill: steelblue;
}
<script src="https://d3js.org/d3.v4.min.js"></script>
Open the console and click / double click on the rect:
<svg width="400" height="110">
<rect width="100" height="100" />
</svg>
Upvotes: 4