Skip to content Skip to sidebar Skip to footer

Selecting An Element Underneath Dragged Element In D3.js

I want to select the element that is underneath the dragged element, WHILE dragging. Selection should be done using the mouse cursor, bounds checking on dragged object is not requi

Solution 1:

You can get mouse events working on objects underneath the dragged object by simply setting its 'pointer-events' to 'none' on dragstart.

function dragstarted(d) {
  d3.select(this).raise().classed("active", true);
  d3.select(this).attr('pointer-events', 'none');
}

Don't forget to remove it on dragend so that the object can be dragged again.

function dragended(d) {
  d3.select(this).attr('pointer-events', null)
  d3.select(this).classed("active", false);
}

Here's @disperse's slightly modified fiddle to show it: https://jsfiddle.net/samuel365/10gLvxde/215/

Solution 2:

One way to accomplish this is to calculate the distance between the centers of the circles:

function dragged(d) {
  d3.select(this).attr("cx", d.x = d3.event.x).attr("cy", d.y = d3.event.y);
  d3.selectAll("circle").each (function(c) {
    if (c !== d) {
      var distance = Math.sqrt( Math.pow((d3.event.x - c.x), 2) + Math.pow((d3.event.y - c.y), 2) );
      if (distance < (radius * 2)) {
        d3.select(this).classed("intersecting", true);
      } else {
        d3.select(this).classed("intersecting", false);
      }
    }
  });
}

Working fiddle here: https://jsfiddle.net/5n6xxhj6/1/

Post a Comment for "Selecting An Element Underneath Dragged Element In D3.js"