Basic Selenium

Drag and Drop Action in Selenium webdriver using Actions class

Hello Welcome to  Selenium WebDriver Tutorials, in this post, we will see how to perform Drag and drop in Selenium web driver using Actions Class.

Selenium has a separate class called Actions Class which is mainly responsible for the complex gesture which includes double click, right-click, mouse hover, keyboard events, and so on.

Actions Class in Selenium WebDriver

 

All application which is available on the web  like all E-commerce like Flipkart, Amazon, Snapdeal they have all advanced activities for example mouse hover, drag and drop and right click etc. In these cases, we will use the Actions class in Selenium.

Drag and Drop in Selenium webdriver

In order to perform drag and drop we have some predefined methods which will do our task. 

Even if you do not want to use dragAndDrop method then still you can do the same operation using clickAndHold, MoveToElement and Release method which we will discuss in this post itself.

Let’s discuss these methods one by one

Drag And Drop Methods in Selenium

1- dragAndDrop(WebElement src,WebElement dest)

This is a very straight forward method where you can simply specify the source and destination and selenium will perform internally clickAndHold > MoveToElement > Release method.

Note- This is only applicable when you can have a clear source and destination.

Step by Step Approach for Drag and Drop

Find the XPath of the Source and find the XPath of destination. 

Both source and destination in form of WebElement.

 

Note- Any method of Actions class we need to call perform () method otherwise we will get an exception. If we have series of action in our script using Actions class then we have to call build().perform() method.

 

 

Drag and drop in Selenium webdriver

package testcases;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class DemoDragDrop {

public static void main(String[] args) throws Exception {

// Initiate browser
WebDriver driver=new FirefoxDriver();

// maximize browser
driver.manage().window().maximize();

// Open webpage
driver.get("http://jqueryui.com/resources/demos/droppable/default.html");

// Add 5 seconds wait
Thread.sleep(5000);

// Create object of actions class
Actions act=new Actions(driver);

// find element which we need to drag
WebElement drag=driver.findElement(By.xpath(".//*[@id='draggable']"));

// find element which we need to drop
WebElement drop=driver.findElement(By.xpath(".//*[@id='droppable']"));

// this will drag element to destination
act.dragAndDrop(drag, drop).build().perform();

}

}

 

Drag and drop in Selenium Webdriver with Source and X and Y Coordinate

If you will see below screenshot then you will notice that we have a source which is a box which can be dropped anywhere in that rectangle box.

In this kind of scenario, we have to use another method where we have to provide Source, X, Y coordinates.

Now the question comes in mind how do we find X, Y coordinate right?

Well we have two approaches to this

First- Find X, Y Coordinates manually by dragging the box and capturing X, Y from the console.

Drop using X,Y

Once you identify X, Y coordinates then just pass the same in the method.

 

Second Approach- You can find X, Y coordinate using Selenium itself and once you find the X, Y then you can changes the coordinates accordingly

WebElement drag=driver.findElement(By.xpath(".//*[@id='draggable']")); int x=drag.getLocation().getX(); int y=drag.getLocation().getY();

Let’s write the actual program which covers the same scenario

package sampleTest;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

public class HandleDropDrop {

	public static void main(String[] args) throws InterruptedException {
		

		System.setProperty("webdriver.chrome.driver", "./src/test/resources/chromedriver.exe");
		
		WebDriver driver=new ChromeDriver();
		
		// Open webpage
		driver.get("http://jqueryui.com/resources/demos/droppable/default.html");

		driver.switchTo().frame(0);
		
		// Add 5 seconds wait
		Thread.sleep(5000);

		// Create object of actions class
		Actions act=new Actions(driver);

		// find element which we need to drag
		WebElement drag=driver.findElement(By.xpath(".//*[@id='draggable']"));
		
		// calling the method and x,y cordinates are random
		act.dragAndDropBy(drag, 250, 150).build().perform();

	}

}

 

Another example of Drag and Drop and My favorite one 

Click and Hold and Release in Selenium

 

This is another example of Drag and Drop where you can use above two methods which we discussed in our first 2 examples or else you can also try series of click events followed by mouse hover then release.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

public class HandleDropDrop {

	public static void main(String[] args) throws InterruptedException {
		

		System.setProperty("webdriver.chrome.driver", "./src/test/resources/chromedriver.exe");
		
		WebDriver driver=new ChromeDriver();
		
		// Open webpage
		driver.get("https://dhtmlx.com/docs/products/dhtmlxTree/");

	
		// Add 5 seconds wait
		Thread.sleep(5000);

		// Create object of actions class
		Actions act=new Actions(driver);

		// find element which we need to drag
		WebElement source=driver.findElement(By.xpath("(//span[text()='Thrillers'])[1]"));
		
		WebElement destination=driver.findElement(By.xpath("(//span[text()='History'])[2]"));
		
		// it will click and hold the triller box and move to element will move cursor to history in another box and then release
		act.clickAndHold(source).pause(2000).moveToElement(destination).release().build().perform();

	}

}

Hope it is clear for you now regarding Drag and Drop. If you want more example then let me know in comment section.

Now if you are comfortable with Basic Selenium, you can check out Advance Selenium Tutorial as well. ?

More updates Learn Automation page

For any query join Selenium group- Selenium Group

author-avatar

About Mukesh Otwani

I am Mukesh Otwani working professional in a beautiful city Bangalore India. I completed by BE from RGPV university Bhopal. I have passion towards automation testing since couple of years I started with Selenium then I got chance to work with other tools like Maven, Ant, Git, GitHub, Jenkins, Sikuli, Selenium Builder etc.

62 thoughts on “Drag and Drop Action in Selenium webdriver using Actions class

  1. Shyam says:

    Hello Mukesh please reply how to take screenshot of canvas element inside irame

    1. Hi Shyam,

      You can use this library https://github.com/pazone/ashot. As such I don’t have any code for the usage of this library. But I’ll post content on this soon.

  2. umesh karkar says:

    HI Mukesh, As i saw your above conversion for canvas tag . Same here, there is canvas related values are there.

    But seems I can able locate the element for source and target locations both but its not working.

    1. Hi Umesh,
      Can you share the code ?

    2. darshan says:

      hello mukesh can you please add some method for drag and drop work slow way bcz above method i am used in replace of touchaction class so i want it wo;rk as per touch action slow bcz i am used logic in my project to perform down scrolling in slow way

      1. Hi Umesh, you can use pause method which will do actions after pause. Example pause(3000) will apply pause after each method.

  3. Jitesh Kumar Singh says:

    Hi Mukesh,

    How can we drag a file from local drive to any web application.
    Let say we have a file in my D:\ driver, and that file we want to drag and drop it in a web application?

    1. Hi Jitesh,

      Selenium doesn’t provide support for such action. You need to use AutoIT or Sikuli to achieve this operation

    2. Norayr says:

      You can do this by JSExecutor

      public void dropFile(File filePath, WebElement target, int offsetX, int offsetY) {
      if (!filePath.exists())
      throw new WebDriverException(“File not found: ” + filePath.toString());

      JavascriptExecutor jse = (JavascriptExecutor) driver;

      String JS_DROP_FILE =
      “var target = arguments[0],” +
      ” offsetX = arguments[1],” +
      ” offsetY = arguments[2],” +
      ” document = target.ownerDocument || document,” +
      ” window = document.defaultView || window;” +
      “” +
      “var input = document.createElement(‘INPUT’);” +
      “input.type = ‘file’;” +
      “input.style.display = ‘none’;” +
      “input.onchange = function () {” +
      ” var rect = target.getBoundingClientRect(),” +
      ” x = rect.left + (offsetX || (rect.width >> 1)),” +
      ” y = rect.top + (offsetY || (rect.height >> 1)),” +
      ” dataTransfer = { files: this.files };” +
      “” +
      ” [‘dragenter’, ‘dragover’, ‘drop’].forEach(function (name) {” +
      ” var evt = document.createEvent(‘MouseEvent’);” +
      ” evt.initMouseEvent(name, !0, !0, window, 0, 0, 0, x, y, !1, !1, !1, !1, 0, null);” +
      ” evt.dataTransfer = dataTransfer;” +
      ” target.dispatchEvent(evt);” +
      ” });” +
      “” +
      ” setTimeout(function () { document.body.removeChild(input); }, 25);” +
      “};” +
      “document.body.appendChild(input);” +
      “return input;”;

      WebElement input = (WebElement) jse.executeScript(JS_DROP_FILE, target, offsetX, offsetY);
      input.sendKeys(filePath.getAbsoluteFile().toString());
      waitFor(ExpectedConditions.stalenessOf(input));
      }

  4. dee says:

    How can we verify if element is dragged and dropped using any conditions ? like if we want to print drag and drop is successful after moving from source to correct destination

    1. Hi Deep,

      After drag and drop action, you can verify whether webelement got changed or not.

  5. Ankur Rana says:

    Hi Mukesh,

    I want to Drag and then drop a element “inbetween” two elements (No element is present in between those two elements). Is it possible if yes then how? Example:

    these are the elements, Now i want to move inbetween and , so my final structure will be

    manually this is possible in our application. li contains folder structure of which i want to change the sequence.

    1. Hi Ankur,

      Just do usual drag and drop action. You only need correct source and target webelement, thats it.

  6. SATVEER BAJWA says:

    Hi Mukesh,
    I ma using drag and drop in my script. It doesn’t act anything juts stopped the script before action class. Please provide me solution

    Actions act=new Actions(driver);

    // find element which we need to drag
    WebElement drag=driver.findElement(By.xpath(“/html/body/div[2]/div[3]/div[6]/div/div[1]/div[2]/div[4]/div[1]/div/div[5]/div/div/div/img”));
    //drop
    WebElement drop=driver.findElement(By.xpath(“/html[1]/body[1]/div[2]/div[1]/div[1]/div[1]/canvas[1]”));

    act.clickAndHold(drag).pause(2000).moveToElement(drop).release().build().perform();

    1. Hi Satveer,

      What error/exception are you getting when your scripts gets stop?

      1. SATVEER BAJWA says:

        Hi Mukesh,

        Thanks for your reply. Now I understand the situation, why script failed because there is canvas element and It is hard to locate the elements inside the canvas. Could you please send me link if you have any tutorial to find the location for elements in canvas.

        1. Hi Satveer,

          Using Selenium, it is almost not possible to locate canvas tag because contents inside this tag are always dynamic.

          1. SATVEER BAJWA says:

            Ohh, Really Are you sure Mukesh It will not possible because I dont want to waste time on these things if it is not possible with selenium . Some online solutions like Actions(driver).moveToElement(). but it is very hard to find the exact location with pixels like

            https://chariotsolutions.com/blog/post/automated-testing-of-html5-canvas/,
            I dont’ know what to do because this is the main scenario in my webpage.

          2. Hi Satveer,

            Into canvas tag you can do some copy paste and roughly some drag and drop actions but it is not advisable to use to use Selenium. As you mentioned, find exact location is not possible. Drag and drop will work but you can’t predict its actual location into canvas. Browser behavior also to be taken into consideration

          3. SATVEER BAJWA says:

            Hi Mukesh,
            Thank you so much for your time. You have given me detailed explanation on this issue. Thanks again Mukesh. Yes now I am looking for other UI tools where I can test this scenario . I will continue other scenarios with selenium.

  7. keerthi says:

    hi mukesh,
    i used pause in my code but its not working

    WebElement main = a.findElement(By.xpath(“//span[text()=’Bestsellers’][1]”));
    WebElement destination=a.findElement(By.xpath(“(//span[text()=’History’])[2]”));
    act.clickAndHold(main).pause(2000).moveToElement(destination).release().build().perform();

    it showing me a warning to add this——> @SuppressWarnings(“deprecation”)

    Please help

    1. Hi Keerthi,

      Latest version of Webdriver(i.e. 3.141.59) won’t throw this warning. Also check this https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/interactions/Actions.html

  8. santhosh says:

    HI Mukesh,

    can u provide any sample drag and drop element with 2 frames
    ex:we should capture the element from frame1 and drop it in frame2

    1. Hi Santosh,

      Do you have any sample application for such scenario, if you have kindly reply me back.

  9. Alam says:

    Hi Mukesh,

    Thank you very much to provide such and valuable post to us. i just tried your code its works fine in system, i checked only in firefox, I actually finding different scenario like drag from local machine and drop in website. such as go to and drag a object from machine and drop on specified area. is there any method available in action or other class?? without using any third party tool…

    1. Hi Alam,

      Actions class comes from Selenium APIs’ and selenium is built for performing actions on webpage only. Therefore usage of third party tool is must if you want to drag and drop an item from your machine to webpage.

  10. Sarayu says:

    Hi Mukesh,

    I have something very similar case, where a drag and drop has to be performed. I tried both of these, but still cannot see the drag and drop happening. On the other hand, the test is not failing as well.
    actions.moveToElement(dragList).clickAndHold(dragList).moveToElement(drophere).release(drophere).build().perform();

    actions.dragAndDrop(dragList, drophere);

    1. can you please provide app url?

  11. Kavitha says:

    Mukesh, I am using latest versions and with gecko driver, action-drag and drop is not working; it is throwing “draganddropaction
    org.openqa.selenium.UnsupportedCommandException” error. Any workaround?

    1. Hi Kavitha,

      Try same with clickAndHold followed by release from Actions class.
      And for your information, there are lot of issues with Selenium 3.X.X version. Its better to downgrade to version 2.53.1 iff previous suggestion doesn’t work.

  12. Surya says:

    Hi Mukesh,
    This script is working on Google Chrome. But when I execute on Firefox then getting exception of “org.openqa.selenium.UnsupportedCommandException: moveto did not match a known command”.

    is any another method to do this task?

    1. Hi Surya,

      Please mention about the version of Selenium and chromedriver you are using?

  13. Stella says:

    Hi Mukesh,

    Is there a solution to automate dragging an image from one iframe to dropping on a grid layout in another iframe.

    Thanks,
    Stella

    1. Hi Stella,

      If you can provide me any sample application then I can guide accordingly.

  14. Amogh says:

    What is difference between build() and perform() method?

    1. Hi Amogh,

      build() is called when you have to compile more than one action in a single step or in simple words it like adding sequence of actions to buffer and later we use perform() to execute it.

  15. Sonia says:

    I used exactly your code, does not work Mukesh. please help. used maximize and thread also…:(

    1. Hi Sonia,

      I just tried and it worked. In which browser you have tried?

  16. Palash says:

    Hi Mukesh,
    Just wanted to know , if the source of the file is my local drive. How will i perform drag and drop functionality.
    Kindly let me know.

    1. Hi Palash,

      Selenium works with browsers only so if you want to work with local drive then you have to check other tools like Sikuli and AutoIT.

  17. Suresh Sharma says:

    Hi Mukesh,

    I implemented Actions class for hovering WebElement and same is working fine with eclipse. But when i run the same script via jenkins it doesn’t work.
    Please suggest what to do!!

    Thanks in advance
    Suresh

    1. Hi Suresh,

      Try to put some wait statement which works for me always.

  18. Khushboo Taneja says:

    Can you please share the video link of drag and drop example. Its will get more helpful.Thanks !!

    1. Yes Khusbhoo will create video soon and will update the same.

  19. Reetanshu says:

    I had gone through the Selenium basics section as of now and I liked all the topics as you have put all the topics in very a simple and self-explanatory way, thank a lot Mukesh for all your efforts.The videos are really good and for a beginner its certainly the best place to learn automation testing

    1. Thanks Reetanshu 🙂 let me know if any help in Selenium

  20. Nikhil says:

    Mukesh above code didnt work an its says unable to find the element.

    1. Hey Nikhil,

      provide code as well

  21. Shantosh says:

    Hi Mukesh,

    Thank you so much for the wonderfull site to learn automation, I know this is the wrong section to put this comment but i dont see a comment section on data driven frame work. Kindly upload Part3 video of data driven framework and also how to call the existing methods of excel if its static methods

    1. Hi Shantosh,

      Part 3 in on the way will upload soon.

  22. grzegorz says:

    I love this page and the way You describe the problems. I’m beginner. Everything is simple when I learning from this site. Than U very much for sharing. Greetings from Poland 🙂

    1. Hi Gorz,

      Thanks a ton 🙂 Keep visiting and let me know if any help from my side.

  23. Sivasankar one s says:

    Hi ,

    I tried to move “One account. All of Google.” text to the Enter your mail id box in the Gmail page . I tried in chrome browser but only space is copied in the box.

    Could you help me on this issue.

    package basic;

    import java.util.ArrayList;

    import org.openqa.selenium.By;
    import org.openqa.selenium.By.ByXPath;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.openqa.selenium.interactions.Action;
    import org.openqa.selenium.interactions.Actions;

    public class MouseMove {

    public static void main(String[] args) throws Exception {
    System.setProperty(“webdriver.chrome.driver”,”C:\\Users\\simuruga\\Desktop\\Docs\\new\\Fileinputstream\\lib\\chromedriver.exe”);
    WebDriver driver =new ChromeDriver();
    Actions action = new Actions(driver);
    driver.get(“https://accounts.google.com/ServiceLogin?service=mail&continue=https://mail.google.com/mail/#identifier”);
    driver.manage().window().maximize();
    WebElement source = driver.findElement(By.xpath(“/html/body/div/div[2]/div[1]/h1”));
    System.out.println(source.getText());
    WebElement target = driver.findElement(By.xpath(“//*[@id=’Email’]”));
    Approach 1:

    action.dragAndDrop( source,target).build().perform();

    Approach 2:

    Actions dragANDdrop = action.clickAndHold(source);

    action.moveToElement(source);
    action.release(target);
    action.build();
    dragANDdrop.perform();

    System.out.println(target.getText());
    }

    }

    1. I guess this is mouse hover activity right?

  24. Vishy says:

    Awesome Mukesh !!!

    1. Thanks Vishy 🙂 Glad to know that you liked this post.

  25. opticyclic says:

    What if I need to drag and drop a file from the Desktop to a file upload div?

    1. Hi Opticyclic,

      Using Selenium Webdriver we can interact with web browser only. From desktop to browser not supported.

      Thanks
      Mukesh

  26. shree says:

    is there any option to drag element and drop it at particular location specially when we don’t have any target element but want to drop as per the x,y cordinate

    1. Hi Shree,

      Yes we have method for this which is present in Actions class.

      Please use below link for more detail about Actions class

      https://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/interactions/Actions.html

      The method which will serve your need is

      Method : dragAndDropBy(source,x-offset,y-offset)
      Parameters: Source, xOffset – horizontal move, y-Offset – vertical move Offset
      Purpose: Performs click and hold at the location of the source element moves by a given off set, then releases the mouse.

      Thanks
      Mukesh

  27. Kannan says:

    Your posts are awesome. It gives me confident to step into automation testing. I thank you personally for all your efforts. Keep posting. 🙂

    1. Thanks Kannan 🙂 Keep visiting..

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.