I'm using jQuery to workaround the drag and drop issue in Selenium. However, I'm a jQuery beginner and I couldn't find an OOTB solution for dropping a JavaScript element at a specific location using jQuery.
The script I'm using is this:
(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) {
/*Simulating drag start*/
var type = 'dragstart';
var event = this.createEvent(type);
this.dispatchEvent(elem, type, event);
/*Simulating drop*/
type = 'drop';
var dropEvent = this.createEvent(type, {});
dropEvent.dataTransfer = event.dataTransfer;
this.dispatchEvent($(options.dropTarget)[0], type, dropEvent);
/*Simulating drag end*/
type = 'dragend';
var dragEndEvent = this.createEvent(type, {});
dragEndEvent.dataTransfer = event.dataTransfer;
this.dispatchEvent(elem, type, dragEndEvent);
},
createEvent: function(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;
},
dispatchEvent: function(elem, type, event) {
if(elem.dispatchEvent) {
elem.dispatchEvent(event);
}else if( elem.fireEvent ) {
elem.fireEvent("on"+type, event);
}
}
});
})(jQuery);
And I'm calling simulateDragDrop
with Selenium's JavascriptExecutor
with 2 JS objects (object to be dragged and destination object). The problems are when I want to drop the first object at a location and not on an object and that it drops it on the upper left corner of the target object.
How can I change the script (or perhaps use a different one) so it will accept a location to drop at (if it's possible...)?
Can I change the script so it will drop at the center of the destination object?
A small note is that it's for automation testing purposes and that the AUT doesn't contain jQuery and I'm injecting it.
A possible solution I thought about is getting an element by it's location using document.elementFromPoint(x, y);
but still it will drop on the upper left corner of this element...