Iter Ator
Iter Ator

Reputation: 9289

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

Upvotes: 3

Views: 2910

Answers (3)

sn_92
sn_92

Reputation: 488

I would really work with HTML5 drag and drop if the browsers you support are recent.
I don't really understand your problem (maybe a jsfiddle?)

If you want to catch the mouse leaving the droppable div, you can use

 droppableDiv.addEventListener("dragleave", function(e) {
 //Do stuff here
 }, false);

If your problem is nothing happens when dragging over the draggable div, try putting a dragover event on the draggable div

 draggableDiv.addEventListener("dragover", function(e) {
 //Do stuff here
 }, false);

Upvotes: 0

Wissam El-Kik
Wissam El-Kik

Reputation: 2525

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

Upvotes: 1

Romeo
Romeo

Reputation: 531

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.

Upvotes: 1

Related Questions