YUI Library Home

Site Search (YDN & YUIBlog):

# YUI Library Examples: Drag & Drop: Dragged Element on Top

# Drag & Drop: 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.

View example in new window.

## 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:

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

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.

<script type="text/javascript"> // Our custom drag and drop implementation, extending YAHOO.util.DD YAHOO.example.DDOnTop = function(id, sGroup, config) { YAHOO.example.DDOnTop.superclass.constructor.apply(this, arguments); }; YAHOO.extend(YAHOO.example.DDOnTop, YAHOO.util.DD, { origZ: 0, startDrag: function(x, y) { YAHOO.log(this.id + " startDrag", "info", "example"); var style = this.getEl().style; // store the original z-index this.origZ = style.zIndex; // The z-index needs to be set very high so the element will indeed be on top style.zIndex = 999; }, endDrag: function(e) { YAHOO.log(this.id + " endDrag", "info", "example"); // restore the original z-index this.getEl().style.zIndex = this.origZ; } }); </script>

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

<script type="text/javascript"> (function() { var dd, dd2, dd3; YAHOO.util.Event.onDOMReady(function() { dd = new YAHOO.example.DDOnTop("dd-demo-1"); dd2 = new YAHOO.example.DDOnTop("dd-demo-2"); dd3 = new YAHOO.example.DDOnTop("dd-demo-3"); }); })(); </script>

## Configuration for This Example

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.

### YUI Logger Output:

### Drag & Drop Examples:

### More Drag & Drop Resources:

- User's Guide (external)
- API Documentation
- Cheat Sheet PDF (external)

Copyright © 2009 Yahoo! Inc. All rights reserved.

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