Drag and drop images in a list : Image Drag Drop « Ajax Layer « JavaScript DHTML

JavaScript DHTML
1. Ajax Layer
2. Data Type
3. Date Time
4. Development
5. Document
6. Event
7. Event onMethod
8. Form Control
9. GUI Components
10. HTML
11. Javascript Collections
12. Javascript Objects
13. Language Basics
14. Node Operation
15. Object Oriented
16. Page Components
17. Security
18. Style Layout
19. Table
20. Utilities
21. Window Browser
Microsoft Office Word 2007 Tutorial
Java
Java Tutorial
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
C# / C Sharp
C# / CSharp Tutorial
ASP.Net
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
PHP
Python
SQL Server / T-SQL
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
JavaScript DHTML » Ajax Layer » Image Drag Drop 
Drag and drop images in a list


<!--

// -------------------------------------------------------------
// Copyright DTLink, LLC 2005.
// by: Yermo Lamers
//
// This software is governed by the new BSD License. Please see the
// accompanying LICENSE.txt file.
//
// See assets/domdrag.js and assets/draglist.js
// 
// For more information please see:
//
//    http://www.formvista.com/otherprojects/draglist.html


?>
-->
<html><head>

<title>DragList - Javascript Drag and Drop Ordered Lists in Javascript</title>
<!-- dom-drag.js -->
<script language="JavaScript" type="text/javascript">
/**************************************************
 * dom-drag.js
 * 09.25.2001
 * www.youngpup.net
 **************************************************
 * 10.28.2001 - fixed minor bug where events
 * sometimes fired off the handle, not the root.
 **************************************************
 * 05.30.2005 - added a workaround for firefox
 * activating links when finished dragging.
 * mmosier@astrolabe.com
 **************************************************/

var Drag = {

  obj : null,

  init : function(o, oRoot, minX, maxX, minY, maxY, bSwapHorzRef, bSwapVertRef, fXMapper, fYMapper)
  {
    o.onmousedown  = Drag.start;

    o.hmode      = bSwapHorzRef ? false true ;
    o.vmode      = bSwapVertRef ? false true ;

    o.root = oRoot && oRoot != null ? oRoot : o ;

    if (o.hmode  && isNaN(parseInt(o.root.style.left  ))) o.root.style.left   = "0px";
    if (o.vmode  && isNaN(parseInt(o.root.style.top   ))) o.root.style.top    = "0px";
    if (!o.hmode && isNaN(parseInt(o.root.style.right ))) o.root.style.right  = "0px";
    if (!o.vmode && isNaN(parseInt(o.root.style.bottom))) o.root.style.bottom = "0px";

    o.minX  = typeof minX != 'undefined' ? minX : null;
    o.minY  = typeof minY != 'undefined' ? minY : null;
    o.maxX  = typeof maxX != 'undefined' ? maxX : null;
    o.maxY  = typeof maxY != 'undefined' ? maxY : null;

    o.xMapper = fXMapper ? fXMapper : null;
    o.yMapper = fYMapper ? fYMapper : null;

    o.root.onDragStart  = new Function();
    o.root.onDragEnd  = new Function();
    o.root.onDrag    = new Function();
  },

  start : function(e)
  {
    var o = Drag.obj = this;
    e = Drag.fixE(e);
    var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
    var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
    o.root.onDragStart(x, y);

    o.startX    = x;
    o.startY    = y;
    o.lastMouseX  = e.clientX;
    o.lastMouseY  = e.clientY;

    if (o.hmode) {
      if (o.minX != null)  o.minMouseX  = e.clientX - x + o.minX;
      if (o.maxX != null)  o.maxMouseX  = o.minMouseX + o.maxX - o.minX;
    else {
      if (o.minX != nullo.maxMouseX = -o.minX + e.clientX + x;
      if (o.maxX != nullo.minMouseX = -o.maxX + e.clientX + x;
    }

    if (o.vmode) {
      if (o.minY != null)  o.minMouseY  = e.clientY - y + o.minY;
      if (o.maxY != null)  o.maxMouseY  = o.minMouseY + o.maxY - o.minY;
    else {
      if (o.minY != nullo.maxMouseY = -o.minY + e.clientY + y;
      if (o.maxY != nullo.minMouseY = -o.maxY + e.clientY + y;
    }

    document.onmousemove  = Drag.drag;
    document.onmouseup    = Drag.end;

    if (o.linkDisabled) {
      var hrefs = o.root.getElementsByTagName("a");
      for (var i = 0; i < hrefs.length; i++) {
        hrefs[i].onclick = hrefs[i].prevOnclick;
        hrefs[i].prevOnclick = null;
      }
      o.linkDisabled = false;
    }

    return false;
  },

  drag : function(e)
  {
    e = Drag.fixE(e);
    var o = Drag.obj;

    var ey  = e.clientY;
    var ex  = e.clientX;
    var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
    var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
    var nx, ny;

    if (o.minX != nullex = o.hmode ? Math.max(ex, o.minMouseX: Math.min(ex, o.maxMouseX);
    if (o.maxX != nullex = o.hmode ? Math.min(ex, o.maxMouseX: Math.max(ex, o.minMouseX);
    if (o.minY != nulley = o.vmode ? Math.max(ey, o.minMouseY: Math.min(ey, o.maxMouseY);
    if (o.maxY != nulley = o.vmode ? Math.min(ey, o.maxMouseY: Math.max(ey, o.minMouseY);

    nx = x + ((ex - o.lastMouseX(o.hmode ? : -1));
    ny = y + ((ey - o.lastMouseY(o.vmode ? : -1));

    if (o.xMapper)    nx = o.xMapper(y)
    else if (o.yMapper)  ny = o.yMapper(x)

    Drag.obj.root.style[o.hmode ? "left" "right"= nx + "px";
    Drag.obj.root.style[o.vmode ? "top" "bottom"= ny + "px";
    Drag.obj.lastMouseX  = ex;
    Drag.obj.lastMouseY  = ey;

    var threshold = 4;
    if (!o.linkDisabled) {
      if (Math.abs(nx - o.startX> threshold || Math.abs(ny - o.startY> threshold) {
        var hrefs = o.root.getElementsByTagName("a");
        for (var i = 0; i < hrefs.length; i++) {
          hrefs[i].prevOnclick = hrefs[i].onclick;
          hrefs[i].onclick = function() { return false};
        }
        o.linkDisabled = true;
      }
    }

    Drag.obj.root.onDrag(nx, ny, Drag.obj.root);
    return false;
  },

  end function()
  {
    document.onmousemove = null;
    document.onmouseup   = null;
    Drag.obj.root.onDragEnd(  parseInt(Drag.obj.root.style[Drag.obj.hmode ? "left" "right"])
                  parseInt(Drag.obj.root.style[Drag.obj.vmode
                                    "top" "bottom"]), Drag.obj.root);
    Drag.obj = null;
  },

  fixE : function(e)
  {
    if (typeof e == 'undefined') e = window.event;
    if (typeof e.layerX == 'undefined') e.layerX = e.offsetX;
    if (typeof e.layerY == 'undefined') e.layerY = e.offsetY;
    return e;
  }
};

</script>

<!-- draglist.js -->
<script language="JavaScript" type="text/javascript">
// ----------------------------------------------------------------------------
// (c) Copyright, DTLink, LLC 1997-2005
//     http://www.dtlink.com
//
// DragList - Drag and Drop Ordered Lists
//
// Javascript Support file for formVista <draglist> fvml tag.
//
// For more information please see:
//
//    http://www.formvista.com/otherprojects/draglist.html
//
// For questions or comments please contact us at:
//
//     http://www.formvista.com/contact.html
//
// LICENSE: This file is governed by the new BSD license. For more information
// please see the LICENSE.txt file accompanying this package. 
//
// REVISION HISTORY:
//
// 2004-11-12 YmL:
//  .  initial revision.
//
// 2005-05-28 YmL:
//  .  pulled out of formVista, relicensed and packaged as a standalone implementation.
//
// 2005-06-02 mtmosier:
//  .  added horizontal dragging support.
//
// ------------------------

/**
* constructor for dragList class
*/

function fv_dragListname )
  {

  // name of this dragList. Must match the id of the root DIV tag.

  this.dragListRootId = name;

  // array of item offsets

  this.offsetsX = new Array();
  this.offsetsY = new Array();

  }

// ----------------------------------------------

/**
* setup the draglist prior to use
*
@param string orientation defaults to vert. if set to "horz" renders horizontally.
@param string itemTagName. if null defaults to "div". Can be "span".
*/

fv_dragList.prototype.setup = functionorientation, itemTagName )
  {

  var horizontal;

  if orientation == "horz" )
    horizontal = true;
  else
    horizontal = false;

  this.listRoot = document.getElementByIdthis.dragListRootId );
  this.listItems = this.getListItemsitemTagName );

  for (var i = 0; i < this.listItems.length; i++
    {

    if this.listItems[i== undefined )
      continue;

    if horizontal )
      {
      Drag.init(this.listItems[i], null, null, null, 00);
      }
    else
      {
      Drag.init(this.listItems[i], null, 00, null, null);
      }

    // ---------------------------------------------------
    // on drag method

    this.listItems[i].onDrag = functionx, y, thisElem 
      {

      x = thisElem.offsetLeft;
      y = thisElem.offsetTop;

      // this is a callback from the dom-drag code. From within this
      // function "this" does not refer to the fv_draglist function.

      draglist = getDragListthisElem );

      draglist.recalcOffsetsitemTagName );

      var pos = draglist.getCurrentOffsetthisElem, itemTagName );

      //var listItems = this.getListItems( itemTagName );

      // if bottom edge is below top of lower item.

      var testMoveUp;
      var testMoveDown;
      if horizontal )
        {
        testMoveUp = (x + draglist.getDivWidth(thisElem> draglist.offsetsX[pos + 1+ draglist.getDivWidthdraglist.listItems[pos + 1] ));
        testMoveDown = x < draglist.offsetsX[pos - 1];
        }
      else
        {
        testMoveUp = (y + draglist.getDivHeight(thisElem> draglist.offsetsY[pos + 1+ draglist.getDivHeightdraglist.listItems[pos + 1] ));
        testMoveDown = y < draglist.offsetsY[pos - 1];
        }

      if (( pos != draglist.listItems.length - 1&& testMoveUp )
        
        draglist.listRoot.removeChild(thisElem);

        if pos + == draglist.listItems.length )
          {
          draglist.listRoot.appendChildthisElem );
          }
        else
          {
          draglist.listRoot.insertBefore(thisElem, draglist.listItems[pos+1]);
          }

        thisElem.style["top""0px";
        thisElem.style["left""0px";
        }
      else if pos != && testMoveDown 
        
        draglist.listRoot.removeChild(thisElem);
        draglist.listRoot.insertBefore(thisElem, draglist.listItems[pos-1]);
        thisElem.style["top""0px";
        thisElem.style["left""0px";
        }

      };

    this.listItems[i].onDragEnd = function(x,y,thisElem
      {
      thisElem.style["top""0px";
      thisElem.style["left""0px";
      }

    }  // end of for loop.

  this.recalcOffsetsitemTagName );

  }  // end of setup.

// ----------------------------------------------


/**
* update the order value fields and submit the form.
*/

fv_dragList.prototype.do_submit = functionformName, dragListRootId )
  {

  var listOrderItems = this.listRoot.getElementsByTagName("input");

  for (var i = 0; i < listOrderItems.length; i++
    {
    listOrderItems[i].value = i;
    }

  expr = "document." + formName + ".submit()";

  evalexpr );
  }

// ----------------------------------------------
// "Private" methods.
// ----------------------------------------------

fv_dragList.prototype.recalcOffsets = functionitemTagName 
  {
  var listItems = this.getListItemsitemTagName );

  for (var i = 0; i < listItems.length; i++
    {
    this.offsetsX[i= listItems[i].offsetLeft;
    this.offsetsY[i= listItems[i].offsetTop;
    }
  }

fv_dragList.prototype.getCurrentOffset = function(elem, itemTagName
  
  var listItems = this.getListItemsitemTagName );

  for (var i = 0; i < listItems.length; i++
    {
    if (listItems[i== elem
      
      return i;
      }
    }
  }

fv_dragList.prototype.getDivWidth = function(elem)                   
  {

  if (( elem == undefined|| elem.offsetWidth == undefined ))
    return);

  value = elem.offsetWidth;
  if (isNaN(value))
    {
    value = 0;
    }

  returnvalue );
  }

fv_dragList.prototype.getDivHeight = function(elem
  {

  if (( elem == undefined|| elem.offsetHeight == undefined ))
    return);

  value = elem.offsetHeight;
  if (isNaN(value))
    {
    value = 25;
    }

  returnvalue );
  }

/**
* return list of draggable items
*/

fv_dragList.prototype.getListItems = functionitemTagName )
  {
  if itemTagName == undefined )
    {
    itemTagName = "div";
    }

  var listItems = this.listRoot.getElementsByTagNameitemTagName );

  returnlistItems );
  }

// end of draglist class definition.

// -------------------------------------

/**
* add a new dragList to the list of draglists on this page
*
* This implementatoin supports multiple managed draglists on
* a single page. The index is contained in a global dragListIndex
* array that must be declared in the page.
*/

function addDragListdraglist )
  {
  dragListIndexdraglist.dragListRootId = draglist;
  }

// -------------------------------------------------------

/**
* given a draggable div element, return the draglist it belongs to
*
@see fv_draglist.prototype.setup
* @todo this should probably be a method inside the draglist class.
*/

function getDragListelem )
  {

  // given a list item return the drag list it belongs to.

  var draglistContainer = elem.parentNode;

  var draglist = dragListIndexdraglistContainer.id ];

  returndraglist );
  }

// END

</script>

</head>

<body leftmargin="0" topmargin="0" bgcolor="#ffffff" marginheight="0" marginwidth="0">

<!-- top of main table -->

<table cellpadding="10" width="100%">
<tbody><tr>
<td colspan="2" align="center" width="100%">
<span class="header">draglist - Drag and Drop Ordered Lists in Javascript</span>
</td>
</tr>
<tr>
<td colspan="2" align="left" width="100%">
<div class="contentText">
This is a demonstration of the draglist Drag and Drop Ordered list implementation used
in the <a href="http://www.formVista.com">formVista</a> business component framework 
by <a href="http://www.dtlink.com">DTLink Software</a>.
<br><br>
You can grab the (dragtext and reorder the items on the list. On pressing submit,
the new order of the items will be sent to the server and displayed.
<br><br>
draglists are enclosed in a wrapping <b>&lt;DIV&gt;</b> tag. Each item in the list
is contained in a draggable div or span. When submit is pressed the list of items is 
queried and the position values are modified. 
<br><br>
For more information see the <a href="http://www.formvista.com/otherprojects/draglist.html">Drag List home page.</a>
</div>
</td>
</tr>

<!--
// ========================== VERTICAL DRAGGING EXAMPLE ========================
-->

<tr>

<td align="center" valign="top">
<br>

<!-- Form Wrapper Table -->
<table border="0" cellpadding="0" cellspacing="0">
<tbody><tr>
<td>

<form name="draglist_form" action="index.php" method="post">

<input type="hidden" name="cmd" value="reorder">
<input type="hidden" name="list" value="vertical">

<!-- Tab Table -->
<table border="0" cellpadding="0" cellspacing="0">
<tbody><tr>

<!-- Tab Table, Left Corner Cell -->
<td width="10"><img src="graphics/flattabsimple_003.gif" alt="" border="0" height="19" width="10"></td>

<!-- Tab Table, Title Cell -->
<td background="graphics/flattabsimple.gif"><div class="flattabsimpleFormTitle">Vertical Dragging Example</div></td>

<!-- Tab Table, Right Corner Cell -->
<td width="10"><img src="graphics/flattabsimple_005.gif" alt="" border="0" height="19" width="13"></td>

</tr>
</tbody></table>
<!-- Tab Table, END -->


<!-- Border Color Table -->
<table class="flattabsimpleFormBorderColor" border="0" cellpadding="1" cellspacing="0">
<tbody><tr><td>

<!-- Background Color Table -->
<table class="flattabsimpleFormTable" border="0" cellpadding="0" cellspacing="0">

<tbody><tr><td><img src="graphics/spacer.gif" border="0" height="10" width="1"></td></tr>

<tr>

<td width="10"><img src="graphics/spacer.gif" border="0" height="1" width="10"></td>

<td valign="top">

<table cellpadding="5" cellspacing="0" width="">
<tbody><tr><td colspan="1" align="left" valign="center" width="">The items below are draggable.</td></tr><tr>
  <td colspan="1">
    <img src="graphics/spacer.gif" height="5" width="1">
  </td>
</tr><tr><td colspan="1" align="left" valign="center" width=""></td></tr>

<tr>
<td colspan="3" align="left">

<!-- 

// -------------------------------------------------------
// Container Div that wraps the list. It contains divs that 
// are draggable. see the assets/default.css stylesheet, 
// the do_submit() method in assets/draglist.js and the
// submit button below.

-->

<div id="draglist_container">

<!-- php  // first draggable div -->

<div style="position: relative; left: 0px; top: 0px;">
<table cellpadding="5" cellspacing="0" width="100%">
  <tbody>
    <tr><td colspan="1" align="left" valign="center" width="">
       <table cellpadding="5" cellspacing="0" width="">
          <tbody>
            <tr><td colspan="1" align="left" valign="center" width="">
            <a target="_blank" href="http://www.java2s.com">
            <img src="http://www.java2s.com/style/logo.png" border="0"></a></td>
            <td colspan="1" align="left" valign="center" width=""></td></tr>
</tbody></table></td><td colspan="1" align="right" valign="center" width="">
                          (Drag 1)</td></tr>
</tbody></table>

<?php 

// If these items were coming from a database, we would use the offset in 
// the draglist_items array to hold the unique key of the item. We make use 
// of the fact that PHP arrays do not have sequential keys to do this.
//
// The value here is the items initial position. the draglist.do_submit() function
// updates these values onSubmit. 

?>

<input name="draglist_items[1]" value="0" type="hidden">

</div>

<!--  // second draggable div -->

<div style="position: relative; left: 0px; top: 0px;">
<table cellpadding="5" cellspacing="0" width="100%">
<tbody><tr><td colspan="1" align="left" valign="center" width="">
<table cellpadding="5" cellspacing="0" width="">
<tbody><tr><td colspan="1" align="left" valign="center" width="">
<a target="_blank" href="http://www.java2s.com">
<img src="http://www.java2s.com/style/logo.png" border="0"></a></td>
<td colspan="1" align="left" valign="center" width=""></td></tr>
</tbody></table></td><td colspan="1" align="right" valign="center" width="">
                          (Drag 2)</td></tr>
</tbody></table>

<input name="draglist_items[2]" value="1" type="hidden">
</div>

<!-- php  // third draggable div -->

<div style="position: relative; left: 0px; top: 0px;">
<table cellpadding="5" cellspacing="0" width="100%">
<tbody><tr><td colspan="1" align="left" valign="center" width="">
<table cellpadding="5" cellspacing="0" width="">
<tbody><tr><td colspan="1" align="left" valign="center" width="">
<a target="_blank" href="http://www.java2s.com.com">
<img src="http://www.java2s.com/style/logo.png" border="0"></a></td>
<td colspan="1" align="left" valign="center" width=""></td></tr>
</tbody></table></td><td colspan="1" align="right" valign="center" width="">
                          (Drag 3)</td></tr>
</tbody></table>

<input name="draglist_items[3]" value="2" type="hidden">
</div>

<!-- php  // fourth draggable div -->

<div style="position: relative; left: 0px; top: 0px;">
<table cellpadding="5" cellspacing="0" width="100%">
<tbody><tr><td colspan="1" align="left" valign="center" width="">
<table cellpadding="5" cellspacing="0" width="">
<tbody><tr><td colspan="1" align="left" valign="center" width="">
<a target="_blank" href="http://www.java2s.com">
<img src="http://www.java2s.com/style/logo.png" border="0"></a></td>
<td colspan="1" align="left" valign="center" width=""></td></tr>
</tbody></table></td><td colspan="1" align="right" valign="center" width="">
                          (Drag 4)</td></tr>
</tbody></table>

<input name="draglist_items[4]" value="3" type="hidden">
</div>

<!-- php  // fifth draggable div -->

<div style="position: relative; left: 0px; top: 0px;">
<table cellpadding="5" cellspacing="0" width="100%">
<tbody><tr><td colspan="1" align="left" valign="center" width="">
<table cellpadding="5" cellspacing="0" width="">
<tbody><tr><td colspan="1" align="left" valign="center" width="">
<a target="_blank" href="http://www.java2s.com">
<img src="http://www.java2s.com/style/logo.png" border="0"></a></td>
<td colspan="1" align="left" valign="center" width=""></td></tr>
</tbody></table></td><td colspan="1" align="right" valign="center" width="">
                          (Drag 5)</td></tr>
</tbody></table>

<input name="draglist_items[5]" value="4" type="hidden">
</div>

<!-- php  // sixth draggable div -->

<div style="position: relative; left: 0px; top: 0px;">
<table cellpadding="5" cellspacing="0" width="100%">
<tbody><tr><td colspan="1" align="left" valign="center" width="">
<table cellpadding="5" cellspacing="0" width="">
<tbody><tr><td colspan="1" align="left" valign="center" width="">
<a target="_blank" href="http://www.java2s.com">
<img src="http://www.java2s.com/style/logo.png" border="0"></a></td>
<td colspan="1" align="left" valign="center" width=""></td></tr>
</tbody></table></td><td colspan="1" align="right" valign="center" width="">
                          (Drag 6)</td></tr>
</tbody></table>

<input name="draglist_items[6]" value="5" type="hidden">
</div>

<!--  // end of draglist_container div -->

</div>

</td>
</tr><tr>
  <td colspan="1">
    <img src="graphics/spacer.gif" height="5" width="1">
  </td>
</tr><tr><td colspan="1" align="center" valign="center" width="">

<!--

// do_submit() queries the new order of the items in the list and 
// updates