Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Both single and double click on a node in d3 force directed graph

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.

like image 326
CrazyCoder Avatar asked Jan 02 '26 00:01

CrazyCoder


1 Answers

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>
like image 118
Mikhail Shabrikov Avatar answered Jan 03 '26 13:01

Mikhail Shabrikov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!