Reputation: 2331
I am using d3 to select rectangle. I am trying to get both a drag end and mouseup event to fire on the rectangle. It looks like the drag events block mouseup events. (They do not block mouse over events) I have bound a mouse up and a drag event to the rectangle. When I click on the rectangle, the mouseup event doesn't fire, only the drag end fires. I have tried different combinations of event.stopPropagation() and preventDefault() to control which events fire. I also tried setting the drag event to null. None of these work. How do I get both the drag end and mouseup to fire on mouseup?
var target = d3.select('#test');
target.on('mouseup', (d) => alert('mouseup'))
.call(d3.drag()
.on("start", function () {
console.log('start')
})
.on("drag", function () {
console.log('drag');
}).on("end", function () {
alert('end');
//d3.select(window).on('click.drag', null);
})
);
<div id='test' />
#test { background:red; position:absolute; height:40px; width:40px; }
This functionality worked in D3 v3 but it does not work in v4
Edit: To clarify, my problem was that the mouseup events are disabled on the page (and for that matter all elements) when the drag events trigger. I wanted to identify the target element when you drag from one shape onto another (hence the need for mouseup).
Upvotes: 3
Views: 2715
Reputation: 2331
When you click on one element and drag to another, I wanted to detect what that second element is. Mouseup doesn't trigger when you drag an object, but mouseover and mouseout do. I used those functions to set a mouseover_obj variable. That way after you drag, when the drag end event executes, you can access that object. If it's not null, then its value that is the shape your mouse is over.
Here's some code: JsFiddle for D3 Mouseup while Drag
var mouseover_node = null;
var svg = d3.select('body').append('svg').attr('width', 1000).attr('height', 1000);
var rect = svg.selectAll('rect')
.data([0, 2, 3])
.enter().append('rect')
.attr('x', function(x) { return +x * 0; })
.attr('y', function(y) { return +y * 120; })
.attr('width', function() { return 100; })
.attr('height', function() { return 100; })
.attr('fill', function(x) { if(x == 0){return'red';}else return 'blue'; });
rect.on("mouseover", (d) => {this.mouseover_node = d})
.on("mouseout", (d) => {this.mouseover_node = null})
.call(d3.drag()
.on("start", function () {
console.log('start');
return false;
})
.on("drag", function () {
console.log('drag');
})
.on("end", (sourceElement,index,svgItems) => {
console.log('end drag with mouseover: ' + this.mouseover_node);
})
);
Upvotes: 2
Reputation: 70
In my experience you should just be able to add mouse down logic into the drag started event. Have you tried that in this case? If it's a more complicated use of mouse down and doesn't work with the drag started event, please add the specifics.
Upvotes: 0