YUI 3.x Home -

Site Search (YDN & YUIBlog):

# YUI Library Examples: Drag & Drop: Drag Constrained to a Region

Note: This is YUI 3.x. Looking for YUI 2.x?

## Drag & Drop: Drag Constrained to a Region

This example shows how to constrain a draggable Node to another Nodes region.

View example in new window.

1
2
3

### Setting up the Node

First we need to create the HTML structure used in this example.

<div id="dd-demo-canvas1"> <div id="dd-demo-canvas2"> <div id="dd-demo-canvas3"> <div id="dd-demo-1" class="dd-demo"><div>1</div></div> <div id="dd-demo-2" class="dd-demo"><div>2</div></div> <div id="dd-demo-3" class="dd-demo"><div>3</div></div> </div> </div> </div>

Now we give the Nodes some CSS to make them visible.

.dd-demo { position: relative; text-align: center; color: #fff; cursor: move; height: 60px; width: 60px; padding: 0; margin: 0; } .dd-demo div { border: 1px solid black; height: 58px; width: 58px; } #dd-demo-canvas1 { padding: 55px; background-color: #004C6D; border: 1px solid black; } #dd-demo-canvas2 { padding: 25px; background-color: #CDCDCD; border: 1px solid black; } #dd-demo-canvas3 { padding: 15px; background-color: #8DD5E7; border: 1px solid black; } #dd-demo-1 { background-color: #8DD5E7; top:5px; left:5px; color: #000; } #dd-demo-2 { background-color: #CDCDCD; top:50px; left:100px; color: #000; } #dd-demo-3 { background-color: #004C6D; top:-100px; left:200px; }

### Setting up the YUI Instance

Now we need to create our YUI instance and tell it to load the `dd-constrain` module (that will load the dd-ddm and dd-drag modules too).

YUI().use('dd-constrain');

### Making the Nodes draggable

Now that we have a YUI instance with the `dd-constrain` module, we need to instantiate the `Drag` instance on the Nodes.

YUI().use('dd-constrain', function(Y) { var dd1 = new Y.DD.Drag({ node: '#dd-demo-1' }); var dd2 = new Y.DD.Drag({ node: '#dd-demo-2' }); var dd3 = new Y.DD.Drag({ node: '#dd-demo-3' }); });

### Constrain the Nodes to other Nodes

Now that we have the Nodes draggable, we need to constrain them. We can do this by plugging the `DDConstrained` on to the `Drag` instance and passing it a config option called `constrain2node` and giving it a selector string of the Node we want to constrain to.

YUI().use('dd-constrain', function(Y) { var dd1 = new Y.DD.Drag({ node: '#dd-demo-1' }).plug(Y.Plugin.DDConstrained, { constrain2node: '#dd-demo-canvas3' }); var dd2 = new Y.DD.Drag({ node: '#dd-demo-2' }).plug(Y.Plugin.DDConstrained, { constrain2node: '#dd-demo-canvas2' }); var dd3 = new Y.DD.Drag({ node: '#dd-demo-3' }).plug(Y.Plugin.DDConstrained, { constrain2node: '#dd-demo-canvas1' }); });

Copyright © 2009 Yahoo! Inc. All rights reserved.

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