Flash Dynamic Stacking Menu

Update: AS3 Version using TweenLite is available here

In this experiment, you can drag the boxes; when you release them the stack will shuffle to accommodate the dropped box.

I have recently been working on building an application in which I wanted to use Photoshop style ‘layers’ which the user could create, drag onto different depths and delete.

The basic idea was for the user to click and drag ‘layers’, and drop them in between others. This would cause the other layers to reposition to accommodate the new layer and to fill the gap which it had left in it’s old position. Get it?

Perhaps I’m just a bit dim, but I was surprised at how many difficulties I encountered when trying to sort the boxes or ‘layers’. I began taking the approach of calculating whether the surrounding layers were above or below, and moving them up or down accordingly; but with this approach I found that deleting layers or adding new ones caused the system to go a bit crazy.

As usual, it was the simple and elegant approach which eventually yielded the solution. I basically handled all of the movement from a single, straightforward array. The array was shuffled based on a nifty little prototype I wrote for extracting and reinserting elements (essentially shuffling without randomness), from which all movement calculations (i.e. the eventual positions of the shuffling boxes) could be made.

Array.prototype.shuffle = function (x, y)
	var i:Number = this.slice (x, x + 1);
	this.splice (x,1);
	this.splice (y,0,i);

The shuffle prototype itself could be very useful, as it pulls items out of the array, and by reinserting them; muscles the other elements outwards around it – no complicated calculations needed for determining where the elements go thanks to some really basic build in Flash Actionscript features. Also, by omitting one line of code, the prototype could be used to simply insert items into an array at a particular position (insertAt(value, index) or something along those lines).

I have attached a bare bones example for you, though I assure you, you can do great things with this script. The menu I was working on will probably make an appearance on Soulwire once the program is finished. One example of its usage would be to associate each box with a layer elsewhere; for example a Stack of photos which are depth ‘shuffled’ through the easy manipulation of their affiliated boxes.

Download: Dynamic Stacking Menu (AS2) Download: Dynamic Stacking Menu (AS3)

You can download the FLA here above, but here is the basic commented code. It is simple but works quite well.

// Include the Zigo tweening prototypes to make life easier
#include "lmc_tween.as"

// Create the main holder for the boxes
var menu:MovieClip = this.createEmptyMovieClip ("menu", 0);
menu._x = menu._y = 20;

// Set up our Arrays and counters
var boxes:Array = new Array ();
var boxCount:Number = 0;
var boxGap:Number = 37;

The core 'SHUFFLE' function
This pulls out an array item at a given index and inserts it back into the array
at another index. The other array items are consiquently 'pushed' outwards from
the element, so our new array reflects the visual appearance we want for the
shuffled menu. We can now 'sort' our menu based on this modified array...
Array.prototype.shuffle = function (x, y)
	var i:Number = this.slice (x, x + 1);
	this.splice (x,1);
	this.splice (y,0,i);

// Our sort function
function sort ()
	var count:Number = boxes.length;
	for (var i = 0; i < count; i++)
		// Check which ID is at this point in the array
		var id:Number = boxes[i];
		// Find the corrosponding box
		var box:MovieClip = eval ("menu.box" + id);
		// Calculate the position the box should be at
		var y:Number = i * boxGap;
		// Alter it's id to it's new position
		box.id = i;
		// Tween it there (or just use box._y = y)
		box.tween ("_y",y,0.8,"easeInOut");

// Creating new boxes
function addBox ()
We use getNextHighestDepth() because of the swapDepths() function used
when the buttons are pressed. This creates new levels and so could
cause problems if we just create boxes at depths based on the length
of the boxes array.
	var d:Number = menu.getNextHighestDepth ();
	var i:Number = boxCount;
	// We could use Push(), but I want the boxes stacked, with newest on top
	boxes.unshift (i);
	// Attach the box
	var box:MovieClip = menu.attachMovie ("box", "box" + i, d);
	// Initiate the box
	box.initBox (i);
	// Increase the counter
	// Sort the boxes
	sort ();

This is a simple function which can be called to remove boxes. It splices the array and
resorts the stack accordingly.
function deleteLayer (id)
	var box:MovieClip = eval ("menu.box" + boxes[id]);
	box.removeMovieClip ();
	boxes.splice (id,1);
	sort ();

// The box actions
MovieClip.prototype.initBox = function (num)
	this.id = num;
	this.name.text = "Box " + num;

	this.onPress = function ()
		var top:Number = boxCount + 1;

		this.swapDepths (top);
		this.startDrag ();

	this.onRelease = this.onReleaseOutside = function ()
		this.stopDrag ();
		// Slide back to the edge
		this.tween ("_x",0,0.8,"easeInOut");
	Find the original position, and the new position, based on the
	location of the draged box in relation to the other boxes.
		var x:Number = this.id;
		var y:Number = Math.round (this._y / boxGap);
		// Call our shuffle function based on these calculations
		boxes.shuffle (x,y);
		// Sort the boxes based on our shuffled array
		sort ();

// Add some boxes to test it!
for (var i = 0; i < 5; i++)
	addBox ();
Posted on 13 Apr 2007
4 Trackbacks


Dynamic Stacking was posted on April 13th 2007 in the category Code / Flash, Open Source and tagged; , , , , .

You can Leave a comment.

Warning: file_get_contents(http://search.twitter.com/search.atom?q=from:soulwire&rpp=1) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 410 Gone in /home/soulwire/webapps/soulwire_blog/wp-content/themes/soulwire/functions.php on line 203


48 Responses to Dynamic Stacking

Leave a Reply

Pingbacks / Trackbacks

  1. 8 years ago Help converting to AS3

    [...] Help converting to AS3 Commenta 27th November , 2008 I found this draggable sortable list thing in AS2 :: http://blog.soulwire.co.uk/flash/act…amic-stacking/ [...]

  2. 8 years ago AS3 Drag and Drop Shuffle Grid Menu Interface

    [...] Dynamic stacking 12% similar Array based menu shuffling [...]

  3. 7 years ago Plasticthinking - unlimited edition » Blog Archive » 好文章推荐 陆续更新

    [...] dynamic stacking soulwire是个超牛的网站(博客),专门介绍一些高端的visual [...]

  4. 6 years ago AS3 Drag Sort Grid Experiment | The Reformation

    [...] orginal file came from the excellent soulwire (JUSTIN WINDLE) at this url; http://blog.soulwire.co.uk/art/dynamic-stacking/ This entry was posted in ActionScript 3 and tagged ActionScript 3, Class, drag, drag n drop, [...]

  1. chand 7 years ago

     [ var names:Array = ["12", "11", "10", "9", "8", "7", "6", "5", "4", "3", "2", "1"]; ] 

    Why the array shown from the end on the boxes. The code reads the array from the last index. Could we change that order instead of populating our array in such a manner as I do above. Any help must be appreciated.


    Reply to this comment

  2. Almog Koren 7 years ago

    Hi does anyone know how to have this work with two columns, with the width of each box being dynamic.

    Reply to this comment

  3. Almog Koren 7 years ago

    Any I could really use the help.

    Reply to this comment

  4. eddiem 7 years ago

    hi kool tut

    but i was wondering if u knew how to do the same thing but with images i already have instead of boxes?

    Reply to this comment

  5. peter 7 years ago

    Hi, this is really great! But I have some problem with AS3 version. Everything works fine until I don’t put boxes into some movieclip.
    So I defined some movieclip and added
    holder.addChild( box );
    and onBoxPress
    holder.setChildIndex( event.currentTarget as Box, numChildren – 1 );
    And it’s working fine only if there are more than 15 items, if less, then nothing happened, I cant drag the items. But when I dont put it to movieclip, then its good. I don’t have any idea, why, do you have some, please?

    Reply to this comment

  6. peter 7 years ago

    Hi, now it’s working for me, I just removed the line setChildIndex in OnBoxPress func… Thanks, it’s really great tutorial…

    Reply to this comment

  7. mart 7 years ago

    Hey Justin,

    Thanks for script, this has been a great help to me and somewhere to start from …

    Im having some peculiar results with the deleteLayer method.

    Im finding in some instances its removing the items from the array (great news) and other times its just emptying the item – which causes issues when the sort method is called.

    Any ideas?

    Thanks in advance

    Reply to this comment

  8. Ant 6 years ago

    Great piece of work. Any help on offer to add a button to the right of each box that will show a unique movie clip when clicked? I’m working with the AS3 version.


    Reply to this comment