Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

d3.js : Differentiate between drag/start/end and click event

As the title says, I have an object, and i need all it's drag and click events. There was some discussion about this issue, but it mainly concerned the click and drag events. (and a reply fiddle didnt work properly)

I have a fiddle here of where I am at. When I drag, click is prevented, but when I click the dragstart and end events fire. I'd like them not to fire when I click, and I'd like click not to fire when I want to drag.

var drag = d3.behavior.drag()
  .origin(function(d){return d})
  .on('drag', function(d){
   d3.select(this).attr('cx', function(d){ return d.x += d3.event.dx });
   d3.select(this).attr('cy', function(d){ return d.y += d3.event.dy });   
   console.log('dragging');
})
.on('dragstart', function(d){
  d3.event.sourceEvent.stopPropagation()
  console.log('drag start');
})
.on('dragend', function(d){
  console.log('drag end');
})

// ..... 

 MySvgElementWith3DStuffOnIt.on('click', function(){
  if(d3.event.defaultPrevented) return;
  console.log('clicked');
});
like image 869
val Avatar asked May 30 '16 20:05

val


People also ask

How to distinguish mouse click and drag?

The basic difference between a click and a drag event is the mouse movement. The mouse event that differentiates a click and drag event is the “mouse move” event. In a “click” event, there is no “mouse move” event. However, the “mouse down” and “mouse up” event remains the same for both click and drag.

What is d3 event?

d3.event. Event object to access standard event fields such as timestamp or methods like preventDefault. d3.mouse(container) Gets the x and y coordinates of the current mouse position in the specified DOM element.


2 Answers

A small update of @thatOneGuy to use d3v4 drag module

https://jsfiddle.net/mhebrard/q5eL5qyv/

var drag = d3.drag()
    .on('drag', function(d){
    d3.select(this).attr('cx', function(d){ return d.x += d3.event.dx });
    d3.select(this).attr('cy', function(d){ return d.y += d3.event.dy });   
    console.log('dragging');
  })
  .on('start', function(d){
    console.log('drag start');
  })
  .on('end', function(d){
    console.log('drag end');
  })
like image 176
Maxime Hebrard Avatar answered Sep 30 '22 05:09

Maxime Hebrard


Your example works as expected. See updated fiddle : https://jsfiddle.net/thatOneGuy/dd4nujxo/1/

I have put a few added console logs. When you drag this line :

if (d3.event.defaultPrevented) {console.log('return'); return};

Will stop the click event from firing. And when you only click, the dragstart and dragend get fired (as expected), but the drag doesn't. Which is why you put the code to move the circle inside the drag function. The whole thing works as expected :)

like image 39
thatOneGuy Avatar answered Sep 30 '22 04:09

thatOneGuy