Cannot Select a DIV After Dragging it into Another DIV Higher up in the DOM

In a small app that I’m tinkering with there are 3 draggable DIVs all of which have the default z-index value of zero and all have a class of “canDrag”. On the page, DIV1 appears above DIV2 and DIV2 appears above DIV3. If I drag DIV1 into DIV2 or DIV3 and then try to select it again to move it out of DIV2 or DIV3, I will not be able to.

It appears that after dragging a DIV into another DIV, releasing the mouse, clicking the left mouse button to reselect it, and then attempting to drag it again, the drag action will fail if the dragged DIV is listed lower in the DOM tree than the DIV that it was dragged into. Also when dragging DIV2 into DIV3 another observed issue is that not only will DIV3 be automatically selected on mousedown but sometimes the mousemove event cannot be removed on mouseup. Usually, the mousemove event can be removed easily if a lower DIV was not dragged into a higher DIV in the DOM and then attempting to drag it.

Why is this happening, how do I reselect a DIV after dragging it into a DIV that is listed higher than itself in the DOM tree, and what is preventing the mousemove event from being removed? Please see my code here

I can’t help with the JS but a css solution would be to set a higher z-index as the elements get smaller so that they will always be selected when the cursor is over them.

e.g.div3 has z-index:1 and then div2 has z-index:2 and lastly div1 has z-index:3

   #DIV1 {
            top: 10px;
            left: 50px;
            width: 40px;
            height: 40px;
            border: solid red 2px;


        #DIV2 {

            top: 65px;
            left: 50px;
            width: 80px;
            height: 80px;
            border: solid green 2px;

        #DIV3 {

            top: 160px;
            left: 50px;
            width: 120px;
            height: 120px;
            border: solid purple 2px;

Is the idea to make it that you can somehow select something that’s been overlapped, or to not allow overlapping?

To see clearer what’s happening, change your div’s to have a background color. You can then see what happens when you drag things on top of each other.

It’s actually the opposite in my browser from what you describe - things added later in the DOM take priority, which… makes more sense, really.

Collision detection is going to be messy, but it can be done.
Alternative to my mind is that when you start to drag an element,it should be shifted in the z-index to the bottom of the pile. There are a couple of ways of doing that… simplest is probably going to be adding 1 to every element’s z-index, and then setting the current element’s to 1. Effectively, send-to-back every time something is selected. Or maybe whenever it’s dropped. Whatever.

I cannot reproduce the issue anymore after adding ev.preventDefault to my eventlistener. Hopefully it will remain that way

1 Like