Drag and Drop directive, no e.clientX or e.clientY when drag and drop in FireFox

I implemented a simple drag and drop system using directives in Angular. It works fine in Chrome, but Firefox does not expose event.clientX, event.clientY events on a drag event (they just refuse to fix it). Therefore, I am looking for a good alternative to expose these properties when dragging:

x, y coordinates are needed for visual feedback during a drag event.

The code is here:

http://plnkr.co/edit/ApeyQ4FcdsA8Ez18Roi0?p=preview

go to Chrome and Firefox to see the problem.

In Chrome, drag an item into folders, you will have the same item as visual feedback, following the mouse, and not in Firefox (since Firefox does not support e.clientX and e.clientY in the drag event).

problem here: (beginning of line 45)

.on('drag', function(e) { if (e.originalEvent.clientX) { el.css({ 'top': e.originalEvent.clientY + 10, 'left': e.originalEvent.clientX + 10 }); } else { el.css('display', 'none'); } }); 

So, how can I get the mouse position on the screen during a drag event in Firefox (angular, I mean with directives, no global variable or anything else)?

enter image description here

+6
source share
2 answers

You can connect to dragover on document - clientX and clientY . Use functional closure to not fill the global area. This updates PLNKR (tested in Chrome and FF).

Changes in js:

 .directive('mpDrag', function($timeout, $window, $document) { // keeping coordinates private and // shared among all instances of the directive var mouseX, mouseY; $document.on("dragover", function(event){ mouseX = event.originalEvent.clientX; mouseY = event.originalEvent.clientY; }) return { ... link: function($scope, element, attrs) { ... $timeout(function() { ... .on('drag', function(e) { // just use mouseX, mouseY directely here // (btw. you should detect differently when to hide the element) console.log(mouseX, mouseY); if (e.originalEvent.clientX) { el.css({ 'top': mouseY, 'left': mouseX }); } else { el.css('display', 'none'); } }); }); } }; }) 
+6
source

You must borrow the drag and drop coordinates from the document itself:

 var dragX = 0, dragY = 0; element.on('dragstart', function(e) { document.ondragover = function(event) { event = event || window.event; dragX = event.pageX, dragY = event.pageY; }; }); element.on('drag', function(e) { el.css({ 'top': dragY + 10, 'left': dragX + 10 }); }); 

Updated plunker: http://plnkr.co/edit/kA58c7Q0vCMpjBfQ1znV?p=preview

EDIT: I sincerely apologize to Arthur Grzhesiak (author of the above answer). I learned my lesson: "Read what others say before posting." Vote for him, as this is a technical error of his decision. Thanks!

+2
source

Source: https://habr.com/ru/post/970170/


All Articles