Drag and Drop Action in Selenium webdriver using Actions class

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 Actions class in Selenium.

For all advance activity in Selenium Webdriver, we can perform easily using Actions class like Drag and Drop, mouse hover, right click, Click and Hold and so on.
We have predefined method called dragAndDrop(source, destination) which is a method of Actions class.


Approach- Find the xpath of the Source and find the xpath of destination.

Both source and destination in form of WebElement.

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
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();
}
}