Yahoo! Developer Network Home - Help

YUI Library Examples: Drag & Drop: Drag and Drop - Staying in a Region

Drag & Drop: Drag and Drop - Staying in a Region

This example shows how to keep draggable elements from being dragged out of a region.

The three elements below will not be able to be dragged beyond the borders of their own colored elements.

1
2
3

Setting up the playing field

First we setup the HTML for the canvas (playing field) and place some players on it.

Size of the playing field

Next we have to get the size of the playing field. To do this, we will use YAHOO.util.Dom.getRegion('dd-demo-canvas'). getRegion will return something like this:

Now we have the top, bottom, left and right pixel locations of the playing field, we can do some math and set some constraints.

The Math

The math for this is pretty easy, as shown in the code below:

It should be noted that the box model comes into play here. Placing padding, margins or borders on the playing field or the draggable elements will cause them to not stay fully in the playing field. They will overlap the region by the width of the margin/padding/border.

Now that we have the vars for top, bottom, left and right, we can set contraints on a Drag Drop instance with setXConstraint and setYConstraint

Full Javascript Source

Copyright © 2008 Yahoo! Inc. All rights reserved.

Privacy Policy - Terms of Service - Copyright Policy - Job Openings