Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drag HTML element: How to handle if the mouse moves outside the div?

I'm creating a draggable div, like in this example: http://jqueryui.com/draggable/

Everything works fine, but if I move the mouse fast, and the mouse leaves the div, then it stops following the mouse. I use elem.addEventListener("mousemove", function(e) {/* ... */}, false); and if I change the last attribute to true, then it still doesn't works as it should be. The div follows the mouse, as long the mouse is inside the div.

I would like to fix it, without using JQuery

like image 640
Iter Ator Avatar asked Jan 25 '26 18:01

Iter Ator


2 Answers

You should use:

 elem.addEventListener("mouseup", function(e) {

 }, false);

 elem.addEventListener("mousemove", function(e) {

 }, false);

 elem.addEventListener("ondragstart", function(e) {

 }, false);

You can find a tutorial to implement Drag-n-Drop using native JavaScript here: http://luke.breuer.com/tutorial/javascript-drag-and-drop-tutorial.aspx

I would recommend the following HTML5 solution

Here's JS Fiddle: http://jsfiddle.net/v4pd25s3/

Also, check a full-fledge HTML5 solution: http://blog.teamtreehouse.com/implementing-native-drag-and-drop

http://blog.teamtreehouse.com/implementing-native-drag-and-drop

like image 109
Wissam El-Kik Avatar answered Jan 28 '26 07:01

Wissam El-Kik


Try to put the mousemove event on the document so it captures the event on the whole page, not only when the mouse hovers the div.

This means that the event will be fired everytime the mouse moves and it is on the page.

like image 31
Romeo Avatar answered Jan 28 '26 07:01

Romeo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!