Created
May 20, 2015 21:02
-
-
Save jdfm/4c5ba4ae8e0e2922796b to your computer and use it in GitHub Desktop.
drag and drop code that uses a state machine to tame the madness
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* I stumbled upon this solution while trying to help out a colleague. | |
* I was studying a book on the theory of computation at the time | |
* which, coincidentally, talked about state machines, it then ocurred | |
* to me that a state machine could help solve the problems we were | |
* having at the time. | |
*/ | |
(function(){ | |
// 0 = not doing anything | |
// 1 = is dragging | |
// 2 = is dragging and entered different element | |
var dragState = 0; | |
document.addEventListener('dragstart', function(e){ console.log('starting drag'); }); | |
document.addEventListener('dragenter', function (e) { | |
switch(dragState){ | |
// first time dragging | |
case 0: | |
dragState = 1; | |
console.log('first drag'); | |
break; | |
// is currently already dragging, and seems to be | |
// entering some other element | |
case 1: | |
dragState = 2; | |
console.log('entered into another element'); | |
break; | |
// undefined for this event | |
default: case 2: break; | |
} | |
}); | |
document.addEventListener('dragover', function(e){ console.log('over an element'); }); | |
document.addEventListener('dragleave', function (e) { | |
switch(dragState){ | |
// if you are here it means you left the first area which | |
// started the dragging process | |
case 1: | |
dragState = 0; | |
console.log('abandoned dragging'); | |
break; | |
// you just left some other element at this point | |
case 2: | |
dragState = 1; | |
console.log('left an element'); | |
break; | |
// undefined for this event | |
default: case 0: break; | |
} | |
}, true); // can't remember why I needed to use true here... | |
document.addEventListener('drag', function(e){ console.log('drag origin'); }); | |
document.addEventListener('drop', function(e){ console.log('drop'); }); | |
document.addEventListener('dragend', function(e){ | |
dragState = 0; | |
}); | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment