javascript - How do I find the position of the draggable element relative to the droppable area -
i using html5 native drag , drop.
i having problems finding position of draggable element relative it's parent container.
summary of task
i have "position: relative" div consider 'droppable area'. inside div, have several "position: absolute" image elements have marked draggable. want these images freely movable user.
to set position of element i've listener on 'dragend'.
the end top / left variables must percentage based opposed pixel.
current attempt
below can see attempt:
draggable.addeventlistener('dragend', function (event) { event.preventdefault(); //gets position of 2 elements relative viewport var droppableboundingrect = droppable.getboundingclientrect(); //establishes percentage using droppable height , width var draggablexpercentage = ((event.clientx - droppableboundingrect.left) / droppable.clientwidth) * 100; var draggableypercentage = ((event.clienty - droppableboundingrect.top) / droppable.clientheight) * 100; //set positional elements of draggable element event.target.style.top = draggableypercentage + "%"; event.target.style.left = draggablexpercentage + "%"; }, false);
and here's jsfiddle of hoping work, comments showing expecting each segment do:
https://jsfiddle.net/ol8yd9lr/
perhaps i'm looking wrong tree, in wrong forest. i'd appreciate guidance.
found possible solution. not perfect should illustrate how can relative position. may have gone little overboard i've commented important parts.
; (function($, undefined) { var dragging; $(function() { $('.dropzone').on({ 'dragover dragenter': dragover, 'drop': drop }).on({ 'dragstart': dragstart, 'dragend': dragend }, '.drag'); }); function dragstart(e) { e.stoppropagation(); var dt = e.originalevent.datatransfer; if (dt) { dt.effectallowed = 'move'; dt.setdata('text/html', ''); dragging = $(this); // set position of mouse relative element @ 0,0 dt.setdragimage(dragging.get(0), 0, 0); } } function dragover(e) { e.stoppropagation(); e.preventdefault(); var dt = e.originalevent.datatransfer; if (dt && dragging) { dt.dropeffect = 'move'; dragging.hide(); // hide element while dragging } return false; } function drop(e) { e.stoppropagation(); e.preventdefault(); if (dragging) { var dropzone = $(this); // offset of dropzone relative window var offset = dropzone.offset(); // set offset of drag relative dropzone dragging.css({ 'top': e.clienty - offset.top, 'left': e.clientx - offset.left }); dragging.trigger('dragend'); // trigger dragend } return false; } function dragend(e) { if (dragging) { dragging.show(); dragging = undefined; } } }(jquery));
Comments
Post a Comment