Skip to the content...

Welcome to the David Walsh Blog. I'm a MooTools, Dojo, jQuery, CSS, and PHP Web Developer located in Madison, Wisconsin, United States. Please contact me if I can make your experience on my website better.

Drag and Drop Z-Index Stacking

28 Responses »
MooTools Drag Opacity »

In an example for a previous post, I showed you how to use opacity during a drag'n'drop transaction. One bit I didn't account for was element stacking and bringing the most recent element to the top of the stack. To do so, we'll need to use a variable that represents the highest zIndex, which we'll be incrementing.

The MooTools JavaScript

window.addEvent('domready',function() {
	var zIndex = 2;
	$$('.draggable').each(function(el) {
		var drag = new Drag.Move(el,{
			grid: false,
			preventDefault: true,
			onStart: function() {
				el.setStyle('z-index',zIndex++); //increment!
			}
		});
	});
});

As you probably expected, the process is as simple as it gets. Correct stacking order is incredibly important as you don't want items to be wrongly buried.

Discussion

  1. January 29, 2010 @ 10:04 am

    I believe z++ should actually be zIndex++ … or you get fail ;)

  2. January 29, 2010 @ 10:13 am

    This Friday’s dumbass mistake brought to you by…lack of sleep.

  3. January 29, 2010 @ 2:38 pm

    Nice idea, although it does not seem to work for me (tested in Chrome/Windows).

    Either way, I think you should do pre-increment instead of post-increment, to assign the incremented value to the element: el.setStyle(‘z-index’, ++zIndex). That way you wont need to start the variable in 2 :)

  4. January 30, 2010 @ 1:26 pm

    Is it just me or did your original referenced topic use z-index stacking as well?

  5. February 2, 2010 @ 2:12 am

    Have a look at the footer on my homepage. I have incorporated dragging functions with jquery for the 4 items. I had hover z-index replace at one point but removed it because it was not realistic with solid gears :) THX

  6. February 2, 2010 @ 2:21 am

    @Brian Klepper: I meant 6 items.. :0

Be Heard!

Share your thoughts with fellow developers of all skill levels! I want to hear from you!

Name*:
Email*:
Website:  
Wrap your code with <code> tags, f00!