CSS absolute positioning prevents jquery ui droppable (sorta)

This is a case of too much drinking while coding for sure.

Working Example
I was trying to implement jquery UI draggables/droppables using the example here.
I made a couple of minor changes to the file to illustrate a point.

  1. I removed the class “ui-widget-header” from the “droppable” div because I wanted to make it a transparent box.
  2. I added “border-style: solid; border-color: red” to droppable so you could still see the box boundaries.

So you can see the results of my edit here in the starting positions of the draggable and droppable.

Image

Next, I moved the draggable box into the droppable box like so:

Image

So far so good. Finally, I drag the draggable outside of the droppable.

Image

 

Alright, looks good to me.

Absolute Positioning F*’s things up (sorta)

Now, I make a minor change to the droppable css again adding “position: absolute; left: 200px”.
“Position: absolute” positions it to an absolute position (duh). “left: 200px” just moves it away from the draggable, otherwise, it would show up right on top of it.

So again, let’s refresh our page and try again from the beginning here:

Image

Then we drag the draggable into the droppable like so

Image

Not bad.

And now let’s drag it out of the… damn it!

You can’t!

So absolute:positioning breaks draggables, right? Better report the bug, right?

Nope. Let’s put the “ui-widget-header” back on “droppable” removing its transparency so we can see what’s going on.

First, let’s remove “position:absolute” from the droppable’s css. And this time, we’re going to drag the draggable just slightly into the droppable, not all the way. It’ll look something like this.

Image

Now, let’s add back “position: absolute” to the droppable’s css, and do the same thing.

Image

Do you see what happened there?

When absolute:positioning is on, the draggable rests underneath the droppable. And because of that, you can’t grab it to drag it out of the droppable.

So we’ve confirmed it: it’s broken, right?

Not so fast.

The Solution

There’s this rarely used css attribute called z-index. This property specifies the layering order of stacked elements. (You didn’t know flat objects on a webpage had depth, did you?)

So we can set the z-index of the droppable to a negative number like -1, to bring the droppable behind the draggable. Or we can set the z-index of the draggable to a higher positive number like 10, to bring the draggable in front of the droppable.

 

Tagged , , , , ,

3 thoughts on “CSS absolute positioning prevents jquery ui droppable (sorta)

  1. awais says:

    Nice info thank you

  2. sandi says:

    Life saver!!Thanks for the solution

Leave a reply to kanesee Cancel reply