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.
First we setup the HTML for the canvas (playing field) and place some players on it.
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 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
You can load the necessary JavaScript and CSS for this example from Yahoo's servers. Click here to load the YUI Dependency Configurator with all of this example's dependencies preconfigured.
Note: Logging and debugging is currently turned off for this example.
Copyright © 2011 Yahoo! Inc. All rights reserved.
Privacy Policy - Terms of Service - Copyright Policy - Job Openings