Stop dragmove event programmatically in D3 v5 - javascript

In a Vue/D3 project, I need to set some restrictions on where some draggable elements may be moved.
This is an excerpt from the dragmove handler:
dragmove: function(d, i, n) {
// Stop if the node crosses a border
if (parseInt(n[i].getAttribute('x')) > 200) {
this.drag.dragend();
}
}
this.drag.dragend(); is taken from an older answer on Stackoverflow. Unfortunately, it does not work in D3 v5 (this.drag.dragend is not a function).
This is my drag variable:
drag: d3.drag()
.on('drag', this.dragmove)
.on('end', this.dragended),
Is there a way to update my code to work with more recent versions of D3?

You can use d3.event.on to temporarily override event listeners. So, to programatically interrupt a drag during the drag event itself, we can use:
d3.event.on("drag", null)
d3.event.on("end", null)
This temporarily removes the functions assigned to each event listener.
You'll note I remove the end event too - otherwise it will continue to listen for mouse up regardless of if a function is assigned to the "drag" event listener.
This functionality is described in d3-drag under event.on:
event.on(typenames, [listener])
Equivalent to drag.on, but only applies to the current drag gesture.
Before the drag gesture starts, a copy of the current drag event
listeners is made. This copy is bound to the current drag gesture and
modified by event.on. This is useful for temporary listeners that only
receive events for the current drag gesture. (source)
In the example below, the drag events are temporarily removed from the circle when it hits the line. A custom event is dispatched to indicate that the drag was programatically interrupted. All events are logged - indicating that end, drag, and interrupt events work as expected:
var svg = d3.select("svg");
var drag = d3.drag()
.on("drag", function() {
log(); // to log events as they are triggered.
var selection = d3.select(this);
// Update the circle as normal (but don't let cx exceed the line visually):
selection.attr("cx", d3.event.x > 300 ? 300 : d3.event.x)
.attr("cy", d3.event.y);
// If event.x > 300, interrupt drag:
if(d3.event.x > 300) {
// Disable the drag events temporarily
d3.event.on("drag", null)
d3.event.on("end", null)
// Optionally trigger some alternative event
selection.dispatch("interrupted");
}
})
.on("end", function() {
log();
})
var circle = svg.select("circle")
.call(drag)
.on("interrupted", function() {
d3.select(this)
.transition()
.attr("fill","orange")
.attr("cx",250)
.transition()
.attr("fill","steelblue");
log();
})
function log() {
console.log(d3.event.type);
}
.as-console-wrapper { max-height: 40% !important; }
circle { cursor: pointer ; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg width="500" height="300">
<circle cx="100" cy="50" fill="steelblue" r="10"></circle>
<line x1="305" x2="305" y1="0" y2="400" stroke-width="1" stroke="black"></line>
</svg>

Related

Binding the same event to SVG g element and it's child

Using D3, I'm trying to bind a drag event to a 'g', group element, and a separate drag event to a child of this group. This seems to be causing issues as only group's drag event fires.
I've read through the specs a bit but don't see anything relating to this. Here's the code:
var group = that.vis.append('g')
.classed('dragger', true)
.attr('transform', 'translate(100, 0)')
.call(drag.on( 'drag', function() {...} )),
box = group.append('rect')
.attr('width', that.width * options.width)
.attr('height', that.height)
.classed('box', true);
var left = group.append('rect')
.attr('width', 4).attr('x', 0)
.attr('height', that.height)
.classed('drag-extend right', true)
.call(drag2.on('drag', function(){...}));
'that.vis' refers to the d3 selection containing the svg element. The d3 drag behaviors were created like so:
var drag = d3.behavior.drag()
.origin(function() {
var string = d3.select(this).attr('transform'),
//string = string.replace(/translate\(/, '');
array = string.match( /translate\((\d+), (\d+)\)/ );
return {
x : parseInt(array[1]),
y : parseInt(array[2])
}
}),
drag2 = d3.behavior.drag()
.origin(function() {
return {
x : d3.select(this).attr('x'),
y : 0
};
});
I need the elements to be grouped in order to move the whole group. My only thought is that when you attach an event handler to a SVG group it attaches that handler to all elements inside it? I'd like to be able to just stop propagation on the second element's drag handler so it doesn't bubble up to the 'g' parent however the second event doesn't seem to be attached at all.
Kind of at loss here, any help would be much appreciated...
UPDATE
So I was able to get this working but not in a way that I would of expected and I'm still interested in what exactly is going on here:
drag2 = d3.behavior.drag()
.origin(function() {
return {
x : d3.select(this).attr('x'),
y : 0
};
}).on( 'drag', shapeBox );
var left = group.append('rect')
.attr('width', 4).attr('x', 0)
.attr('height', that.height)
.classed('drag-extend right', true)
.call(drag2.on('dragstart', function(){...}));
function shapeBox() { ... }
For some reason adding the 'dragstart' handler somehow got the drag handler attached directly to the behavior to fire. This is strange because in looking at the d3 docs and from my knowledge of the DOM (which may be somewhat limited), I should have just been able to pass the 'drag2' variable to call.
Not sure what binding the extra listener did but somehow that got the drag to work.

How to stop d3.drag triggering mouseover/mouseout events in chrome

I have the following d3 visualisation. The darker colour at the top indicates that a node has been selected. When I mouseover a non selected node it changes opacity so a user can see which node would be selected if I click.
This is achieved via a CSS style sheet and the following js/d3:
nodeSelection.select("circle").on('mouseover', function(e) {
d3.select(this).classed("hover", true);
_this.fireDataEvent("mouseOverNode", this);
});
nodeSelection.select("circle").on('mouseout', function(e) {
d3.select(this).classed("hover", false);
_this.fireDataEvent("mouseOutNode", this);
});
So, far, so good. However, when I drag, the drag function seems to randomly trigger mouse over and mouse out events on the nodes that I am not dragging. This causes the node opacity to flicker. If I watch on the development tools in chrome I can see that this is because it is causing nodes to gain the class "hover". The code above to add this CSS class appears nowhere else, and by use of the console logging, I have confirmed that mouseover and mouseout events are being fired. These nodes are often far from the cursor.
This issue does not occur in Firefox.
UPDATE: I actually managed to fix this almost immediately after posting this. I just explicitly de-register the listeners inside drag start, and re register in drag end. It might still be interesting to some people if they are having similar issues.
My drag function now looks like:
var drag = d3.behavior.drag()
.on("dragstart", function(d) {
console.log("dragstart");
d.dragstart = d3.mouse(this); // store this
d.fixedbeforedrag = d.fixed;
d.fixed=true;
// deregister listeners
nodeSelection.select("circle").on("mouseover", null).on("mouseout", null);
})
.on("drag", function(d) {
d.px = d.x; // previous x
d.py = d.y;
var m = d3.mouse(this);
d.x += m[0] - d.dragstart[0];
d.y += m[1] - d.dragstart[1];
nodeSelection.attr("transform", "translate(" + [d.x, d.y] + ")");
_this.getForce().start();
})
.on("dragend", function(d) {
console.log("dragend");
delete d.dragstart;
d.fixed = d.fixedbeforedrag;
//reregisters listeners
_this.updateSVG();
});

How to make into d3.js v3.4 the same behavior drag as into v3.1?

I've next code:
vis.forceRep.circle.enter()
.append("g")
.attr("class", "cRepo")
.attr("transform", tr)
.on("mouseover.select", vis.meRepo)
.on("mouseout.select", vis.mlRepo)
.on("mousemove.mtt", vis.mtt)
.on("click.select", vis.clRepo)
.call(vis.forceRep.drag)
;
Into v3.1 we've got the following behavior:
Dragging is not select a node. (MouseDown -> MouseMove -> MouseUp).
Click is select a node. (MouseDown -> MouseUp).
Now into v3.2+:
Drag == Click. That is after dragging after MouseUp.drag the Click event is raised.
How to fix it?
Solution is
vis.clRepo = function() {
if (d3.event.defaultPrevented)
return;
/* handle the click event */
}
found in this answer

d3.js force cancel a drag event

I have a simple drag event - and if a certain condition is met, I'd like to force cancel the drag currently under way (basically as if you were doing a mouseup).
Something like so:
var drag_behavior = d3.behavior.drag()
.on("drag", function() {
if(mycondition){
// cancel the drag event
}
});
EDIT:
the goal is simply to prevent people from dragging a world map outside certain boundaries in such a way that renders the map in mid-ocean (details below).
Current map code:
var width = window.innerWidth
var height = window.innerHeight
var projection = d3.geo.mercator()
.scale((width + 1) / 2 / Math.PI)
.translate([width / 2, height/1.5])
.precision(.1);
var path = d3.geo.path()
.projection(projection);
var drag_behavior_map = d3.behavior.drag()
.on("drag", function() {
drag_click = true //used later to prevent dragend to fire off a click event
d3.event.sourceEvent.stopPropagation();
// original idea
// if(worldmap_left_boundary > 0 || worldmap_right_boundary < screen.height){
// cancel or limit the drag here
// }
});
var svg = d3.select("#map").append("svg")
.attr("width", width)
.attr("height", height)
.call(drag_behavior_map)
Basically this should not be possible.
Inside the drag event function, you can use mycondition to decide whether or not to update the dragged element's position. Not updating the position essentially means stopping the drag.
You could also unsubscribe from the drag event:
var drag_behavior = d3.behavior.drag()
.on("drag", function() {
if(mycondition) {
// cancel the drag event
drag_behavior.on("drag", null);
}
});
Note, there would still be a dragend event, unless you unsubscribe that one too.
Alternatively –– though I'm not totally familiar with triggering native events and how that affects d3.behavior.drag() –– you can try triggering a native mouseup event and see what happens.
var drag_behavior = d3.behavior.drag()
.on("drag", function() {
if(mycondition) {
// "this" is the dragged dom element
this.dispatchEvent(new Event('mouseup'))
}
});

D3 SVG I want to highlight an array of elements by mouse dragging

I have an SVG container with a number of elements each containing a rect and some text elements in a horizontal array.
I want to click on one element and drag to one of the others. The first element and element dragged over should highlight - as it would in a normal text editor selection.
at the end I want to know the first and last elements selected so that I can access their data.
I tried this using d3 drag behaviour but:
1. the intermediate elements can't be highlighted
2. the dragend does not tell me which element was the final one.
Also tried using mouse events but:
1. I can highlight each intermediate item but not easily remove the highlight if the mouse is moved back towards the beginning.
2. if the mouse is moved out of the container I can miss the mouse up events leaving highlighted elements.
3. I still don't really know upon which element I am finishing unless I collect all the mouse over events.
I don't actually want to move the selected elements - just know the first and last one selected.
I created this fiddle to illustrate the problem: http://jsfiddle.net/avowkind/up54b/5/
HTML
<svg class='demosvg' version="1.1"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" >
<rect width="400" height="220"></rect>
<g id="container" transform="translate(10,10)"></g>
</svg>
Javascript
var mydata = [1, 2, 3, 4, 5];
/* each box is a group with a rect and text
positioned according to the data value
on drag/drop we want to know the dragged element, and the one it is dropped on.
we would like to highlight all the intervening elements too.
Ultimately we just want a result e.g. 2 was dragged to 5
*/
var boxg = d3.select('#container').selectAll('g').data(mydata).enter()
.append('svg:g')
.attr('id', function (d, i) {
return "b" + d;
})
.attr('transform', function (d, i) { return "translate(" + d * 50 + ",80)";})
.call(d3.behavior.drag()
.on("dragstart", function (d, i) {d3.select(this).classed("selected", true); })
.on("drag", function (d, i) {
// which element are we over here - to highlight it
var el = document.elementFromPoint(d3.event.x, d3.event.y);
console.log(el);
})
.on("dragend", function (d, i) {
console.log(d);
console.log(this);
console.log(d3.event);
// turn off all highlights
d3.selectAll('#container g').classed("selected", false);
// Which box got dropped on here ?
})
);
boxg.append('svg:rect')
.classed('box', true)
.attr('width', 40).attr('height', 40);
boxg.append('svg:text')
.text(function(d,i) { return d; })
.attr('dx', 15).attr('dy', 20);
CSS
.demosvg { fill:silver;}
.box { fill:lightblue;}
text { fill:black;}
.selected .box{ fill:gold;}
Thanks Andrew

Categories