Pete Alvin
Pete Alvin

Reputation: 4790

HTML5: dragover(), drop(): how get current x,y coordinates?

How does one determine the (x,y) coordinates while dragging "dragover" and after the drop ("drop") in HTML5 DnD?

I found a webpage that describes x,y for dragover (look at e.offsetX and e.layerX to see if set for various browsers but for the life of me they ARE NOT set).

What do you use for the drop(e) function to find out WHERE in the current drop target it was actually dropped?

I'm writing an online circuit design app and my drop target is large.

Do I need to drop down to mouse-level to find out x,y or does HTML5 provided a higher level abstraction?

Upvotes: 27

Views: 46878

Answers (3)

robertc
robertc

Reputation: 75707

The properties clientX and clientY should be set (in modern browsers):


function drag_over(event) {
        console.log(event.clientX);
        console.log(event.clientY);
        event.preventDefault();
        return false;
    }
    function drop(event) {
        console.log(event.clientX);
        console.log(event.clientY);
        event.preventDefault();
        return false;
    }

Here's a (somewhat) practical example that works in Firefox and Chrome.

Upvotes: 30

onyedikachi23
onyedikachi23

Reputation: 47

You can use the pageX and pageY properties of the event object which return the coordinates of the mouse pointer relative to the top-left corner of the document:

/* events fired on the draggable target */
const source = document.getElementById("draggable");
source.addEventListener("drag", (event) => {
    const [x, y] = [event.pageX, event.pageY];
    console.log(`The element is being dragged at (${x}, ${y})`);
});
body {
    background-color: rgb(1, 1, 25);
    /* Prevent the user selecting text in the example */
    user-select: none;
}

#draggable {
    text-align: center;
    background: white;
}

.dropzone {
    width: 200px;
    height: 20px;
    background: blueviolet;
    margin: 10px;
    padding: 10px;
}
<div class="dropzone">
    <div id="draggable" draggable="true">This div is draggable</div>
</div>

Upvotes: 1

Mateja Petrovic
Mateja Petrovic

Reputation: 4317

To build on top of robertc's answer and work around the issue:

The clientX and clientY are going to be inaccurate proportional to the distance of the cursor from the upper left corner of the element which was dropped.

You may simply calculate the delta distance by subtracting the client coords recorded at dragStart from the client coords recorded at dragEnd. Bear in mind the the element which was dropped still has the exact same position at dragEnd which you may update by the delta distance to get the new left and top positional coordinates.

Here's an demo in react, although the same can be accomplished in plain JS.

Upvotes: 4

Related Questions