2

I have been trying this many hours and couldn't get it working. I have an element with d3 that is draggable using drag behavior, and I want to add a dblclick event, so it performs an action when it is double clicked. I couldn't get the dblclick event to be reached. I have studied many ways of trying to stop propagation from within the drag, and changing the order of the declaration of events, with no success so far. My code is like:

switch = box.append('rect')
    .data([{x: point.x, y: point.y}])
    .attr('transform', function (d) { return 'translate(' + d.x + ',' + d.y + ')'; })
    .attr('height', 8)
    .attr('width', 8)
    .attr('stroke', color)
    .attr('fill', color)
    .on('dblclick', function () {
      d3.event.stopPropagation();
      alert('Hello');  // Doesn't enter
    }, true).call(d3.behavior.drag().on('dragstart', function () {
      d3.event.sourceEvent.stopPropagation();
    }).on('drag', function (d) {
      d.x += d3.event.dx;
      d.y += d3.event.dy;
      d3.select(this).attr('transform', 'translate(' + d.x + ',' + d.y + ')');
    }).on('dragend', function (d) {
    }));

Note the "true" after the on('dblclick', ..., true) declaration. I was trying to prevent the propagation.

Any help is appreciated.

cserpell
  • 716
  • 1
  • 7
  • 17
  • [This question](https://stackoverflow.com/questions/19931307/d3-differentiate-between-click-and-drag-for-an-element-which-has-a-drag-behavior) may help. – Lars Kotthoff Jul 23 '15 at 19:55
  • Firstly, you shouldn't have a `;` at the end of this line `.attr('fill', color);`. Secondly, what browser are you using, because your code is working in mine (Chrome)? – D Malan Jul 23 '15 at 21:58
  • I am sorry, the `;` was because of the copy paste here. It is not present in my code. I am using Chrome 43. – cserpell Jul 23 '15 at 22:55
  • @LarsKotthoff I read all those questions and tried everything they mention, but that works with click event and I couldn't get them working with dblclick. I also checked examples with layout drag force and dblclick that work. But I have a drag behavior, not a force. – cserpell Jul 24 '15 at 14:17
  • 2
    I finally solved this the ugly way: I checked in dragend event if the initial and final position is the same, assuming it is a click, and I check if two clicks happen in less than a fixed number of milliseconds. – cserpell Jul 24 '15 at 16:04

1 Answers1

0

Maybe it's an asynchronous event in dragEndHandler that loses focus on the first click, bdlclick isn't fired. So I check if mouseStartPosition is the same in dragEndHandler to return early.

  mouseStartPosition = {
    x: 0,
    y: 0
  }

  dragStartHandler(e: MouseEvent) {
    this.mouseStartPosition = { x: e.x, y: e.y};
  }

  dragEndHandler(e: MouseEvent) {
    if(e.x === this.mouseStartPosition.x && e.y === this.mouseStartPosition.y) return
    // TODO
  }

zayn
  • 26
  • 3