Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
drag_and_drop_helper.js
(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);
@songwk

This comment has been minimized.

Copy link

commented Jun 19, 2013

Hi,
I am using selenium2.33 to drag and drop a HTML5 applicaiton, when I use this js file, I meet such problem in Eclipse. Any comment about this??

"message": "unknown error: Runtime.evaluate threw exception: SyntaxError: Unexpected end of input\n (Session info: chrome=27.0.1453.110)\n (Driver info: chromedriver=2.0,platform=Windows NT 6.1 SP1 x86_64)"

code snippet

    //Drag 1st control to layout
    String js_filepath = "c:\\selenium-java-2.33.0\\drag_and_drop_helper.js";
    String java_script="";
    String text;

    BufferedReader input = new BufferedReader(new FileReader(js_filepath));
    StringBuffer buffer = new StringBuffer();

    while ((text = input.readLine()) != null)
        buffer.append(text + " ");
        java_script = buffer.toString();

    input.close();

    String source = "__htmlview0--Button1";
    String target = "__htmlview0--homePage-intHeader";
    java_script = java_script+"$('#"+source+"').simulate( '#" +target+ "');" ;
    ((JavascriptExecutor)driver).executeScript(java_script);
@dlai0001

This comment has been minimized.

Copy link

commented Feb 25, 2014

Thanks for posting this gist.

Currently I'm using this one to do my drag and drops, https://github.com/jquery/jquery-simulate/blob/master/jquery.simulate.js

I think I like the syntax of yours better

@mharris717

This comment has been minimized.

Copy link

commented Oct 17, 2014

This is awesome, stole some of it to test an ember lib

@hgillane

This comment has been minimized.

Copy link

commented Nov 20, 2014

You are amazing. Thank you so much❗️

@hgillane

This comment has been minimized.

Copy link

commented Nov 20, 2014

This also works with Zepto if you change the last line.

@bhavanishankar

This comment has been minimized.

Copy link

commented May 16, 2015

How to use this helper js in angularjs project using protractor for writing e2e test cases?

@betelgeuse

This comment has been minimized.

Copy link

commented Jun 30, 2015

@rcorreia what's the license on this code?

@lenntt

This comment has been minimized.

Copy link

commented Jul 9, 2015

Thanks a lot!

I needed drag drop across frames, and my application uses DataTransfer#types, which wasn't set.
Added a fix for both in: https://gist.github.com/SirLenz0rlot/cc5baa5a73f188f62f6f

@dudumanbogdan

This comment has been minimized.

Copy link

commented Aug 11, 2015

Thank you! Worked for me!

@Kuniwak

This comment has been minimized.

Copy link

commented Nov 25, 2015

Thanks you.

I studied the approach and I wrote a simular module, but it does not require jQuery.
https://github.com/Kuniwak/html-dnd

It can work on no-jQuery environments.

@Neeta5042

This comment has been minimized.

Copy link

commented Dec 13, 2015

I want to drag and drop using Selenium C#. Not able to do it through actions class. Please any1 provide javascript and how to use it for selenium C#

@myerramalli

This comment has been minimized.

Copy link

commented Apr 20, 2016

I am not able to execute the java script. I am using Java and JUnit and to execute the script I am using the following code :
//Drag 1st control to layout
String js_filepath = ;
String java_script="";
String text;

BufferedReader input = new BufferedReader(new FileReader(js_filepath));
StringBuffer buffer = new StringBuffer();

while ((text = input.readLine()) != null)
    buffer.append(text + " ");
    java_script = buffer.toString();

input.close();

String source = "<source id>";
String target = "<target id>";
java_script = java_script+"$('#"+source+"').simulate( '#" +target+ "');" ;
((JavascriptExecutor)driver).executeScript(java_script);

I am getting the following error :
org.openqa.selenium.WebDriverException: unknown error: Runtime.evaluate threw exception: SyntaxError: Unexpected end of input

How can I solve this issue

@sampathgoud42

This comment has been minimized.

Copy link

commented May 5, 2016

Thanks a bunch for the information.

I just want to know how to implement for xpath selectors for source and target?

Thank you!

@rodikno

This comment has been minimized.

Copy link

commented Jun 5, 2016

Thank you a lot!

Using this to test HTML5 D&D by executing it in Selenium for Ruby.

@Ranjeet-Naidu

This comment has been minimized.

Copy link

commented Jun 14, 2016

This works great when you have a drop zone. I am trying to implement this on a list of draggable items with no luck. Is there a way to dispatch the 'drag' event with x, y coordinates?

@joankaradimov

This comment has been minimized.

Copy link

commented Sep 15, 2016

I've tried using this with a library called ember-drag-drop. Everything works great in general, but for some specific cases the library in question relies on the dragover event. I've added handling for it here:
https://gist.github.com/joankaradimov/81389270b5e820b1558030fd566190fa

I've based it on SirLenz0rlot's fork of the gist:
https://gist.github.com/SirLenz0rlot/cc5baa5a73f188f62f6f

@mohanngs

This comment has been minimized.

Copy link

commented Oct 6, 2016

Please any one can help me through this code..I want to perform drag and drop of multiple images..The area i want to drop is a canvas area. i am able t0 drag and drop to that area but i cant drop into specified location or offset values..images are overlapping on each other in one location only..Below is the code snippet..i hav used both javascript executor and action class..

    WebElement source =oBrowser.findElement(By.xpath("//*[@id='tabImg']/ul/li[1]/img"));
    Thread.sleep(5000);
    WebElement target = oBrowser.findElement(By.xpath("//div[@id='canvas']/div/canvas"));
    Thread.sleep(5000);

    Actions actionBuilder=new Actions(oBrowser);          
    Action drawOnCanvas=actionBuilder
                    .moveToElement(source,223, 184)
                    .clickAndHold(source)
                    .moveToElement(target)
                    .moveToElement(target,326, 277)
                    .release(source)
                    .build();
    drawOnCanvas.perform();
    actionBuilder.dragAndDrop(source, target).build().perform();
    Thread.sleep(5000);

JavascriptExecutor js1=((JavascriptExecutor)oBrowser);
js1.executeScript("function createEvent(typeOfEvent) {\n" +
"var event = document.createEvent("CustomEvent");\n" +
"event.initCustomEvent(typeOfEvent, true, true, null);\n" +
" event.dataTransfer = {\n" +
" data: {},\n" +
" setData: function (key, value) {\n" +
" this.data[key] = value;\n" +
" },\n" +
" getData: function (key) {\n" +
" return this.data[key];\n" +
" }\n" +
" };\n" +
" return event;\n" +
"}\n" +
"\n" +
"function dispatchEvent(element, event, transferData) {\n" +
" if (transferData !== undefined) {\n" +
" event.dataTransfer = transferData;\n" +
" }\n" +
" if (element.dispatchEvent) {\n" +
" element.dispatchEvent(event);\n" +
" } else if (element.fireEvent) {\n" +
" element.fireEvent("on" + event.type,event);\n" +
" }\n" +
"}\n" +
"\n" +
"function simulateHTML5DragAndDrop(element, target) {\n" +
" var dragStartEvent =createEvent('dragstart');\n" +
" dispatchEvent(element, dragStartEvent);\n" +
" var dropEvent = createEvent('drop');\n" +
" dispatchEvent(target, dropEvent,dragStartEvent.dataTransfer);\n" +
" var dragEndEvent = createEvent('dragend'); \n" +
" dispatchEvent(element, dragEndEvent,dropEvent.dataTransfer);\n" +
"}\n" +
"\n" +
"var source = arguments[0];\n" +
"var target = arguments[1];\n" +
"simulateHTML5DragAndDrop(source,target);", source, target);

@Gaurav0

This comment has been minimized.

Copy link

commented Oct 11, 2016

Could you clarify the license for this gist?

@rahilliard1

This comment has been minimized.

Copy link

commented Mar 30, 2017

I am getting the following error using this code: org.openqa.selenium.WebDriverException: unknown error: Runtime.evaluate threw exception: SyntaxError: Unexpected end of input

Anyone have any insight into the issue? Note: it worked fine just two weeks ago.

@Cst2989

This comment has been minimized.

Copy link

commented May 16, 2017

Hello, I used your script to make drag and drop work in codeception using webdriver. For anyone who was having the same problem, this is what I did:

Created a file dnd.js Added in the file the entire jquery library.(my app is in angular2 so it doesn't have jQuery). At the end of the app added This simulatedraganddrop js. And at the end end added jQuery('#style-0').simulateDragDrop({ dropTarget: '#dd-top'});

And in codeception:
$this->executeInSelenium(function(\Facebook\WebDriver\Remote\RemoteWebDriver $webdriver) { $script = file_get_contents('/Users/neciudan/Desktop/apps/codeception/tests/_support/Page/dnd.js'); $webdriver->executeScript($script); }); $this->wait(10);

Hope this helps other people who couldn't figure this out in Codeception.

@skducn

This comment has been minimized.

Copy link

commented Jun 27, 2018

hello, How to use it in Python.

@anupamdas24

This comment has been minimized.

Copy link

commented Jun 29, 2018

Can some one please provide some code in Java for Drag and Drop operation using js helper.

@atulparate

This comment has been minimized.

Copy link

commented Aug 2, 2018

Hi All,
I am also facing the same issue. Unable to perform drag and drop operation using protractor on HTML 5 application.

I am using typescript as a language. Please suggest how to use above solution in my case i.e. in typescript. Anyone used above solution if yes then please let me know is that working or not.

Thanks in advance.

@sergsol

This comment has been minimized.

Copy link

commented Aug 16, 2018

If someone has an example how to use it with python, please share

@kelanmomo

This comment has been minimized.

Copy link

commented Sep 17, 2018

I tested a simple sample with Python,it works well.Thanks you very much for your share.
I also referred this : http://elementalselenium.com/tips/39-drag-and-drop

# coding = utf-8
from selenium import webdriver
import os
from time import sleep

driver = webdriver.Chrome()
driver.implicitly_wait(10)
driver.get('http://the-internet.herokuapp.com/drag_and_drop')

with open(os.path.abspath('drag_and_drop_helper.js'), 'r') as js_file:
    line = js_file.readline()
    script = ''
    while line:
        script += line 
        line = js_file.readline()

driver.execute_script(script + "$('#column-a').simulateDragDrop({ dropTarget: '#column-b'});")
sleep(2)
driver.quit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.