Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save valfirst/7f36c8755676cdf8943a8a8f08eab2e3 to your computer and use it in GitHub Desktop.
Save valfirst/7f36c8755676cdf8943a8a8f08eab2e3 to your computer and use it in GitHub Desktop.
Create the `simulateDragDrop` function which can be used to simulate clicking and dragging one DOM Node onto another
function simulateDragDrop(sourceNode, destinationNode) {
var EVENT_TYPES = {
DRAG_START: 'dragstart',
MOUSEOVER: 'mouseover',
DROP: 'drop',
DRAG_END: 'dragend'
}
function createCustomEvent(type) {
var event = document.createEvent('CustomEvent')
event.initCustomEvent(type, true, true, null)
event.dataTransfer = {
data: {
},
setData: function(type, val) {
this.data[type] = val
},
getData: function(type) {
return this.data[type]
}
}
return event
}
function dispatchEvent(node, type, event) {
if (node.dispatchEvent) {
return node.dispatchEvent(event)
}
if (node.fireEvent) {
return node.fireEvent('on' + type, event)
}
}
var event = createCustomEvent(EVENT_TYPES.DRAG_START)
dispatchEvent(sourceNode, EVENT_TYPES.DRAG_START, event)
var mouseoverEvent = document.createEvent('MouseEvent');
mouseoverEvent.initMouseEvent(EVENT_TYPES.MOUSEOVER, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
dispatchEvent(destinationNode, EVENT_TYPES.MOUSEOVER, mouseoverEvent)
var dropEvent = createCustomEvent(EVENT_TYPES.DROP)
dropEvent.dataTransfer = event.dataTransfer
dispatchEvent(destinationNode, EVENT_TYPES.DROP, dropEvent)
var dragEndEvent = createCustomEvent(EVENT_TYPES.DRAG_END)
dragEndEvent.dataTransfer = event.dataTransfer
dispatchEvent(sourceNode, EVENT_TYPES.DRAG_END, dragEndEvent)
}
@valfirst
Copy link
Author

Forked from https://gist.github.com/douglaslise/884692bb54cdf8e76702c01bc18defbd, added simulation of mouseover event after drag event to avoid errors thrown by DnD JS libraries.
For example, https://github.com/react-dnd/react-dnd/ throws the following error

Uncaught Invariant Violation: Cannot call hover while not dragging.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment