</>

Technology

Selenium

Difficulty

Intermediate

Interview Question

How to do drag and drop in Selenium?

Use Actions class with dragAndDrop() or clickAndHold + moveToElement + release to perform drag and drop in Selenium.

Answer

Use the Actions class to perform drag and drop operations.

Method 1: dragAndDrop() — simplest:

Java
Actions act = new Actions(driver);
act.dragAndDrop(sourceElement, targetElement).build().perform();

Method 2: clickAndHold + moveToElement + release:

Java
Actions act = new Actions(driver);
act.clickAndHold(sourceElement)
   .moveToElement(targetElement)
   .release()
   .build()
   .perform();

Method 3: Move by offset (pixel-based):

Java
Actions act = new Actions(driver);
act.clickAndHold(sourceElement)
   .moveByOffset(200, 0)
   .release()
   .perform();

Full test example:

Java
@Test
public void dragAndDropTest() {
    driver.get("https://jqueryui.com/droppable/");
    driver.switchTo().frame(driver.findElement(By.className("demo-frame")));

    WebElement source = driver.findElement(By.id("draggable"));
    WebElement target = driver.findElement(By.id("droppable"));

    new Actions(driver).dragAndDrop(source, target).perform();

    String result = driver.findElement(By.id("droppable")).getText();
    Assert.assertEquals(result, "Dropped!");
}

Note: If dragAndDrop() does not work, try Method 2. Some HTML5 drag implementations require a JavaScript-based approach.

Follow AutomateQA

Related Topics