Reputation: 1921
When I'm clicking and dragging an item. Is there a way to forcefully make it stop being draggable without letting go of the mouse button?
For example, if I drag an item across a certain boundary box, can I make it let go of the dragged item?
Upvotes: 3
Views: 1646
Reputation: 322
jsfiddle example. I forked a drag example from another user, have added a working boundary in the code. Click to create a circle, then drag it over the blue box to see it working.
The concept here is to observe the x & y coordinates in d3.event
while an object is being dragged, then trigger the 'stop' event one of two ways as shown below. The drawback is that until the drag event receives a mouseUp, it throws an error while the mouse is still being held down.
// Define drag beavior
var drag = d3.behavior.drag()
.on("drag", dragmove);
function dragmove(d) {
// if the event.x goes over a boundry, trigger "dragend"
if(d3.event.x > 200){
// using D3
drag.dragend();
// or using jquery
drag.trigger("dragend");
}
var x = d3.event.x;
var y = d3.event.y;
d3.select(this).attr("transform", "translate(" + x + "," + y + ")");
}
The boundary here is based on one variable - x location, but can be extended to be based on the surface area of a shape.
Drag is being used as the namespace for this event, an event for which D3 creates a dispatcher object (see the D3 library code). That can be accessed by calling the event name (for example)
drag.on("eventName", functionToDo)
drag.eventName();
Or if you want to use JQuery
then a trigger can be applied using:
drag.trigger("dragend")
Attaching a mouseover event to a 'boundary box' doesn't work as the object being dragged would be between the mouse and the box. Maybe there is a workaround there also. I have included another smaller red box (open the console to see this not working).
sources:
https://github.com/mbostock/d3/wiki/Drag-Behavior
https://github.com/mbostock/d3/wiki/Internals#dispatch_on
http://api.jquery.com/trigger/
Upvotes: 1