Skip to content

Instantly share code, notes, and snippets.

@vieron
Created August 1, 2014 19:55
Show Gist options
  • Save vieron/ec0a1178ff0ad94cfe3a to your computer and use it in GitHub Desktop.
Save vieron/ec0a1178ff0ad94cfe3a to your computer and use it in GitHub Desktop.
(function($) {
$.fn.simulateDragDrop = function (options) {
return this.each(function () {
new $.simulateDragDrop(this, options);
});
};
$.simulateDragDrop = function (elem, options) {
this.options = options;
this.simulateEvent(elem, options);
};
$.extend($.simulateDragDrop.prototype, {
simulateEvent: function (elem, options) {
var $source = $(elem);
var $target = $(options.dropTarget);
var init_offset = $source.offset();
var target_offset = $target.offset();
init_offset.top += $source.height() / 2;
init_offset.left += $source.width() / 2;
target_offset.top += $target.height() / 2;
target_offset.left += $target.width() / 2;
/*Simulating drag start*/
var type = 'mousedown';
var event = this.createEvent(type, init_offset);
this.dispatchEvent(elem, type, event);
/*Simulating drop*/
type = 'mousemove';
this.dispatchEvent(elem, type, this.createEvent(type, {
top: init_offset.top + 2,
left: init_offset.left + 2
}));
this.dispatchEvent(elem, type, this.createEvent(type, target_offset));
/*Simulating drag end*/
type = 'mouseup';
var dragEndEvent = this.createEvent(type, target_offset);
this.dispatchEvent(elem, type, dragEndEvent);
},
createEvent: function (type, offset) {
var event = document.createEvent("MouseEvents");
event.initMouseEvent(type, true, true, window, 0, 0, 0,
offset.left, offset.top, false, false, false, false, 0, null);
return event;
},
dispatchEvent: function (elem, type, event) {
if (elem.dispatchEvent) {
elem.dispatchEvent(event);
} else if ( elem.fireEvent ) {
elem.fireEvent("on"+type, event);
}
}
});
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment