YUI Library Examples: Drag & Drop: Drag and Drop with the Dragged Element on Top

Drag & Drop: Drag and Drop with the Dragged Element on Top

This example builds on the basic drag and drop, keeping the dragged element on top of the others by changing its z-index property during the drag.

Basic Drag and Drop

The YUI Drag and Drop Utility lets you make HTML elements draggable.

For this example, we will enable drag and drop for the three <div> elements.

Create the demo elements:

1<div id="dd-demo-1" class="dd-demo"></div> 
2<div id="dd-demo-2" class="dd-demo"></div> 
3<div id="dd-demo-3" class="dd-demo"></div> 
view plain | print | ?

Next, we define a custom drag and drop implementation that extends YAHOO.util.DD. Drag and drop exposes many interesting moments that you can use to implement custom functionality. In this example, we override the startDrag and endDrag moments to adjust the z-index property so that the dragged element is always on top.

1<script type="text/javascript"
2 
3// Our custom drag and drop implementation, extending YAHOO.util.DD 
4YAHOO.example.DDOnTop = function(id, sGroup, config) { 
5    YAHOO.example.DDOnTop.superclass.constructor.apply(this, arguments); 
6}; 
7 
8YAHOO.extend(YAHOO.example.DDOnTop, YAHOO.util.DD, { 
9    origZ: 0, 
10 
11    startDrag: function(x, y) { 
12        YAHOO.log(this.id + " startDrag""info""example"); 
13 
14        var style = this.getEl().style; 
15 
16        // store the original z-index 
17        this.origZ = style.zIndex; 
18 
19        // The z-index needs to be set very high so the element will indeed be on top 
20        style.zIndex = 999; 
21    }, 
22 
23    endDrag: function(e) { 
24        YAHOO.log(this.id + " endDrag""info""example"); 
25 
26        // restore the original z-index 
27        this.getEl().style.zIndex = this.origZ; 
28    } 
29}); 
30 
31</script> 
view plain | print | ?

Now we create the instances of YAHOO.example.DDOnTop, passing the element ids or references for our demo elements.

1<script type="text/javascript"
2 
3(function() { 
4 
5    var dd, dd2, dd3; 
6    YAHOO.util.Event.onDOMReady(function() { 
7        dd = new YAHOO.example.DDOnTop("dd-demo-1"); 
8        dd2 = new YAHOO.example.DDOnTop("dd-demo-2"); 
9        dd3 = new YAHOO.example.DDOnTop("dd-demo-3"); 
10    }); 
11 
12})(); 
13 
14</script> 
view plain | print | ?

YUI Logger Output:

Logger Console

INFO280ms (+12) 9:13:12 AM:

global

id is not a string, assuming it is an HTMLElement

INFO268ms (+267) 9:13:12 AM:

DragDropMgr

DragDropMgr onload

INFO1ms (+1) 9:13:12 AM:

global

Logger initialized

More Drag & Drop Resources:

Copyright © 2008 Yahoo! Inc. All rights reserved.

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