Accepted answer

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 

       // or using jquery 
  var x = d3.event.x;
  var y = d3.event.y;"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)

Or if you want to use JQuery then a trigger can be applied using:


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).


Related Query