Search code examples
javascriptjquerydrag-and-dropdojomouseup

Trouble getting xy coordinates in Chrome when using Dojo DND onto a Canvas


I have a project that uses the Dojo framework (1.12.1) and JQuery (2.1.4). I am using the Dojo DND (Drag and Drop) function, but I need to find an XY offset into a canvas element that is a DND Target on drop. I am able to use a JQuery on mouse-up event to collect the offset in Firefox, Safari and it did work in Chrome 51.0.2704.84, but that does not work for me in Chrome 56.0.2924.87, IE or on touch screens (tablets, phones).

I need to find a way to get the XY coordinates within a canvas target for the drop part of drag and drop in at least Chrome as well as Firefox. I don't know if I have overlooked something within Dojo that will do this, or in JQuery, or if something browser-specific has to be done.

The application I'm working on is at https://avida-ed.beacon-center.org/app/AvidaED.html

I have a JSFiddle that shows the problem: https://jsfiddle.net/56bcrk5s/5/

require(['dojo',
    "dojo/dnd/Source",
    "dojo/dnd/Target",
    "dojo/dnd/Manager",
    "dojo/domReady!"
    ], function(dojo, dndSource, dndTarget, dndManager) 
{
    var theList = new dndSource('theList', {
    accept: ['b', 'v', 'd'],singular: true, 
    copyOnly: true, selfAccept: false
    });
    theList.insertNodes(false, [
        {data: 'Rusty', type:['d']},
        {data: 'Farli', type:['v']},
        {data: 'Ritka', type:['v']},
        {data: 'Beka', type:['d']}
    ]);
    myTarget = new dndTarget('myTarget', {accept: ['d', 'v']});
    var xy=[];

    $(document).on('mouseup', function(evt) {
        xy = [evt.offsetX, evt.offsetY];
    });
    myTarget.on('DndDrop', function (source, nodes, copy, target) {
        if ('myTarget' == target.node.id) {
            console.log(nodes[0].textContent,' at ', xy);
            output.textContent = nodes[0].textContent 
                +' at ' + xy[0] +', '+xy[1];
        }
    });
    console.log('dom is ready');
});

Solution

  • More recent versions of Chrome have moved away from providing the desired offsets via "mouseup". The relevant event is now "pointerup". I've tested this in the JSFiddle, and it now works in Chrome. Add this handler:

    $(document).on('pointerup', function(evt) {
        console.log("pointerup evt", evt);
        xy = [evt.originalEvent.offsetX, evt.originalEvent.offsetY];    
    });
    

    and you should see the relevant offsets appear in the console.log output. I haven't tested it with Firefox, so you may need to set up handlers based on browser detection.