How to automate drag & drop functionality using Selenium WebDriver Java?


The drag and drop action is done with the help of a mouse. It happens when we drag and then place an element from one place to another. This is a common scenario when we try to move a file from one folder to another by simply drag and drop action.

Selenium uses the Actions class to perform the drag drop action. The dragAndDrop(source, destination) is a method under Actions class to do drag and drop operation. The method will first do a left click on the element, then continue the click to hold the source element. Next it shall move to the destination location and release the mouse.

Our aim to drag and drop the first box to the second box.

Example

Code Implementation.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.interactions.Actions;
public class DragDrop{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://jqueryui.com/droppable/";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.switchTo().frame(0);
      // identify source and target element
      WebElement s=driver.findElement(By.("draggable"));
      WebElement t=driver.findElement(By.("droppable"));
      /Actions class with dragAndDrop()
      Actions act = new Actions(driver);
      act.dragAndDrop(s, t).build().perform();
      driver.quit();
   }
}

Output

Updated on: 28-Aug-2020

492 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements