Popular Searches
Popular Course Categories
Popular Courses

Drag and Drop

Mouse & Keyboard Actions

Drag and Drop in Selenium WebDriver

Drag and Drop is a common mouse interaction used in modern web applications. It allows a user to click and hold an element, move it to another location, and release it there. In Selenium WebDriver, drag-and-drop operations can be automated using the Actions class.

Drag and Drop automation is useful when testing sortable lists, Kanban boards, dashboards, shopping carts, task-management systems, file-management interfaces, workflow applications, and other web elements that depend on mouse movement.

Selenium Training Course | Register for Course Demo


1. What is Drag and Drop?

Drag and Drop is a mouse interaction in which a user selects an element, holds the mouse button, moves the pointer to another location, and releases the element.

In Selenium Java, the Actions class provides methods such as dragAndDrop(), clickAndHold(), moveToElement(), and release() for automating drag-and-drop interactions.


2. Why is Drag and Drop Important in Selenium?

Many modern web applications depend on mouse-based movement. A normal click() is not sufficient when an application requires an element to be dragged from one location to another.

  • Automates real-world mouse interactions.
  • Tests sortable lists and boards.
  • Validates custom drag-and-drop components.
  • Tests shopping cart interactions.
  • Supports dashboard and workflow testing.
  • Automates task-management workflows.
  • Improves coverage of advanced UI functionality.


3. Drag and Drop in Selenium WebDriver

Selenium WebDriver provides the Actions class for advanced mouse and keyboard interactions. The simplest drag-and-drop operation can be performed using the dragAndDrop() method.

Actions actions = new Actions(driver);

actions.dragAndDrop(source, target).perform();


4. Actions Class

The Actions class is part of Selenium's interaction API. It is commonly used for advanced interactions such as mouse movement, double click, right click, drag and drop, click and hold, hover, and keyboard combinations.

Actions actions = new Actions(driver);


5. Basic Drag and Drop Syntax

Actions actions = new Actions(driver);

actions.dragAndDrop(sourceElement, targetElement).perform();

Here:

  • actions is the Actions object.
  • dragAndDrop(sourceElement, targetElement) performs the drag-and-drop interaction.
  • perform() executes the built interaction.


6. Import Required Classes

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;


7. Simple Drag and Drop Example

WebDriver driver = new ChromeDriver();

 

driver.get("https://example.com");

 

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

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

 

Actions actions = new Actions(driver);

actions.dragAndDrop(source, target).perform();


8. Drag and Drop Using ID Locator

If both the source and target elements have unique IDs, ID locators can be used.

WebElement source = driver.findElement(By.id("dragSource"));

WebElement target = driver.findElement(By.id("dropTarget"));

 

new Actions(driver)

    .dragAndDrop(source, target)

    .perform();


9. Drag and Drop Using Name Locator

WebElement source = driver.findElement(By.name("source"));

WebElement target = driver.findElement(By.name("target"));

 

new Actions(driver)

    .dragAndDrop(source, target)

    .perform();


10. Drag and Drop Using Class Name

WebElement source = driver.findElement(By.className("draggable"));

WebElement target = driver.findElement(By.className("droppable"));

 

new Actions(driver)

    .dragAndDrop(source, target)

    .perform();


11. Drag and Drop Using CSS Selector

WebElement source = driver.findElement(

    By.cssSelector(".drag-source")

);

 

WebElement target = driver.findElement(

    By.cssSelector(".drop-target")

);

 

new Actions(driver)

    .dragAndDrop(source, target)

    .perform();


12. Drag and Drop Using XPath

WebElement source = driver.findElement(

    By.xpath("//div[@id='source']")

);

 

WebElement target = driver.findElement(

    By.xpath("//div[@id='target']")

);

 

new Actions(driver)

    .dragAndDrop(source, target)

    .perform();


13. Drag and Drop from One Element to Another

The most common scenario is moving one WebElement onto another WebElement.

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

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

 

Actions actions = new Actions(driver);

actions.dragAndDrop(source, target).perform();


14. Drag and Drop Method

The dragAndDrop() method provides a concise way to perform a drag-and-drop interaction between two WebElements.

actions.dragAndDrop(source, target).perform();

Conceptually, the operation is:

Locate Source

     ↓

Click and Hold

     ↓

Move Pointer

     ↓

Move to Target

     ↓

Release Mouse

     ↓

Validate Result


15. Drag and Drop Using clickAndHold()

When the direct dragAndDrop() method does not work reliably with a custom component, the interaction can be constructed manually.

Actions actions = new Actions(driver);

 

actions.clickAndHold(source)

       .moveToElement(target)

       .release()

       .perform();


16. Drag and Drop Using moveToElement()

new Actions(driver)

    .clickAndHold(source)

    .moveToElement(target)

    .release()

    .perform();

This approach provides more control over the individual steps of the interaction.


17. Drag and Drop Using release()

The release() method releases the currently held mouse button.

Actions actions = new Actions(driver);

 

actions.clickAndHold(source)

       .moveToElement(target)

       .release()

       .perform();


18. Drag and Drop Using clickAndHold and Move

For applications with complex drag-and-drop behavior, breaking the operation into individual actions can provide better control.

Actions actions = new Actions(driver);

 

actions.moveToElement(source)

       .clickAndHold()

       .moveToElement(target)

       .release()

       .perform();


19. Difference Between dragAndDrop() and Manual Actions

FeaturedragAndDrop()Manual Actions
Code lengthShortLonger
ControlLess controlMore control
Ease of useSimpleRequires more knowledge
Complex UIMay require troubleshootingCan be customized
Typical useStandard drag and dropCustom drag-and-drop components


20. Complete Drag and Drop Program

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 DragAndDropExample {

    public static void main(String[] args) {

 

        WebDriver driver = new ChromeDriver();

 

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

        driver.get("https://example.com");

 

        WebElement source = driver.findElement(

            By.id("source")

        );

 

        WebElement target = driver.findElement(

            By.id("target")

        );

 

        Actions actions = new Actions(driver);

        actions.dragAndDrop(source, target).perform();

 

        driver.quit();

    }

}


21. Drag and Drop with Explicit Wait

Dynamic applications may require the source and target elements to become available before the interaction is performed.

WebDriverWait wait =

    new WebDriverWait(driver, Duration.ofSeconds(10));

 

WebElement source = wait.until(

    ExpectedConditions.elementToBeClickable(

        By.id("source")

    )

);

 

WebElement target = wait.until(

    ExpectedConditions.visibilityOfElementLocated(

        By.id("target")

    )

);

 

new Actions(driver)

    .dragAndDrop(source, target)

    .perform();


22. Required Explicit Wait Imports

import java.time.Duration;

import org.openqa.selenium.support.ui.ExpectedConditions;

import org.openqa.selenium.support.ui.WebDriverWait;


23. Why Explicit Wait is Useful?

  • Handles dynamically loaded elements.
  • Reduces timing-related failures.
  • Waits for the required application state.
  • Improves test stability.
  • Reduces unnecessary hard-coded delays.


24. Avoid Hard-Coded Sleep

Using Thread.sleep() may make tests slower and does not guarantee that the required UI state has actually been reached.

Thread.sleep(3000);

actions.dragAndDrop(source, target).perform();

A condition-based explicit wait is generally preferable when synchronization is required.


25. Drag and Drop on Dynamic Elements

Dynamic web applications may create or update source and target elements after page loading. In such cases, locate the elements after the relevant state is available.

WebDriverWait wait =

    new WebDriverWait(driver, Duration.ofSeconds(10));

 

WebElement source = wait.until(

    ExpectedConditions.visibilityOfElementLocated(

        By.cssSelector(".dynamic-source")

    )

);

 

WebElement target = wait.until(

    ExpectedConditions.visibilityOfElementLocated(

        By.cssSelector(".dynamic-target")

    )

);

 

new Actions(driver)

    .dragAndDrop(source, target)

    .perform();


26. Drag and Drop in a Sortable List

Sortable lists allow users to rearrange items by dragging one item above or below another item.

WebElement firstItem = driver.findElement(

    By.cssSelector(".sortable-item:nth-child(1)")

);

 

WebElement secondItem = driver.findElement(

    By.cssSelector(".sortable-item:nth-child(2)")

);

 

new Actions(driver)

    .dragAndDrop(firstItem, secondItem)

    .perform();


27. Drag and Drop in a Kanban Board

Kanban applications commonly allow users to move tasks between columns such as To Do, In Progress, and Completed.

WebElement task = driver.findElement(

    By.cssSelector(".task-card")

);

 

WebElement completedColumn = driver.findElement(

    By.cssSelector(".completed-column")

);

 

new Actions(driver)

    .dragAndDrop(task, completedColumn)

    .perform();


28. Drag and Drop in a Shopping Cart

An e-commerce application may allow a user to drag a product into a shopping cart.

WebElement product = driver.findElement(

    By.cssSelector(".product-card")

);

 

WebElement cart = driver.findElement(

    By.id("cart")

);

 

new Actions(driver)

    .dragAndDrop(product, cart)

    .perform();


29. Drag and Drop File Upload Area

Some web applications provide a visual drop zone where files can be dragged. When an <input type="file"> is available, Selenium's file-input support is generally more reliable than trying to automate an operating-system file drag operation.

WebElement fileInput = driver.findElement(

    By.cssSelector("input[type='file']")

);

 

fileInput.sendKeys("/path/to/test-file.pdf");

This approach uploads the file directly instead of trying to simulate an operating-system file drag operation.


30. Drag and Drop in a Dashboard

Dashboard applications may allow users to rearrange widgets by dragging them to different positions.

WebElement widget = driver.findElement(

    By.id("salesWidget")

);

 

WebElement targetArea = driver.findElement(

    By.id("dashboardArea")

);

 

new Actions(driver)

    .dragAndDrop(widget, targetArea)

    .perform();


31. Drag and Drop Between Containers

Applications may contain separate source and destination containers. The element can be moved from one container to another.

WebElement item = driver.findElement(

    By.cssSelector(".source-container .item")

);

 

WebElement destination = driver.findElement(

    By.cssSelector(".destination-container")

);

 

new Actions(driver)

    .dragAndDrop(item, destination)

    .perform();


32. Drag and Drop and Verify Result

After performing a drag-and-drop operation, the expected result should always be validated.

new Actions(driver)

    .dragAndDrop(source, target)

    .perform();

 

WebElement result = driver.findElement(

    By.id("successMessage")

);

 

if (result.isDisplayed()) {

    System.out.println("Drag and drop successful");

}


33. Drag and Drop with TestNG Assertion

new Actions(driver)

    .dragAndDrop(source, target)

    .perform();

 

WebElement result = driver.findElement(

    By.id("successMessage")

);

 

Assert.assertTrue(

    result.isDisplayed(),

    "Expected result was not displayed after drag and drop"

);


34. TestNG Drag and Drop Test

@Test

public void verifyDragAndDrop() {

 

    WebElement source = driver.findElement(

        By.id("source")

    );

 

    WebElement target = driver.findElement(

        By.id("target")

    );

 

    new Actions(driver)

        .dragAndDrop(source, target)

        .perform();

 

    Assert.assertTrue(

        driver.findElement(By.id("result")).isDisplayed()

    );

}


35. Drag and Drop in Page Object Model

In the Page Object Model, the drag-and-drop operation can be encapsulated inside the page class.

public void dragItemToTarget() {

 

    WebElement source = driver.findElement(

        By.id("source")

    );

 

    WebElement target = driver.findElement(

        By.id("target")

    );

 

    new Actions(driver)

        .dragAndDrop(source, target)

        .perform();

}


36. Page Object Model Example

public class KanbanPage {

 

    private WebDriver driver;

 

    private By task = By.id("task");

    private By completedColumn = By.id("completed");

 

    public KanbanPage(WebDriver driver) {

        this.driver = driver;

    }

 

    public void moveTaskToCompleted() {

 

        WebElement source =

            driver.findElement(task);

 

        WebElement target =

            driver.findElement(completedColumn);

 

        new Actions(driver)

            .dragAndDrop(source, target)

            .perform();

    }

}


37. Calling Drag and Drop from Test Class

@Test

public void moveTask() {

 

    KanbanPage page =

        new KanbanPage(driver);

 

    page.moveTaskToCompleted();

}


38. Reusable Drag and Drop Utility

public class ActionUtils {

 

    private WebDriver driver;

 

    public ActionUtils(WebDriver driver) {

        this.driver = driver;

    }

 

    public void dragAndDrop(

        WebElement source,

        WebElement target

    ) {

        new Actions(driver)

            .dragAndDrop(source, target)

            .perform();

    }

}


39. Using the Drag and Drop Utility

ActionUtils actions =

    new ActionUtils(driver);

 

WebElement source = driver.findElement(

    By.id("source")

);

 

WebElement target = driver.findElement(

    By.id("target")

);

 

actions.dragAndDrop(source, target);


40. Manual Drag and Drop Utility

A utility can also expose the manual action sequence for applications where direct dragAndDrop() requires customization.

public void manualDragAndDrop(

    WebElement source,

    WebElement target

) {

    new Actions(driver)

        .moveToElement(source)

        .clickAndHold()

        .moveToElement(target)

        .release()

        .perform();

}


41. Drag and Drop with Pause

Some applications require a short pause while the pointer is being moved. The Actions API can include pauses in the interaction sequence when appropriate.

new Actions(driver)

    .moveToElement(source)

    .clickAndHold()

    .pause(Duration.ofMillis(500))

    .moveToElement(target)

    .pause(Duration.ofMillis(500))

    .release()

    .perform();


42. Drag and Drop with Multiple Moves

Complex interfaces may require the pointer to pass through an intermediate location.

new Actions(driver)

    .moveToElement(source)

    .clickAndHold()

    .moveByOffset(100, 0)

    .moveToElement(target)

    .release()

    .perform();


43. Drag and Drop Using moveByOffset()

The moveByOffset() method moves the pointer relative to its current position.

new Actions(driver)

    .moveToElement(source)

    .clickAndHold()

    .moveByOffset(200, 100)

    .release()

    .perform();

Coordinate-based movement should be used carefully because layout changes can affect coordinates.


44. Drag and Drop to a Specific Offset

Some custom interfaces require the item to be dropped at a specific position relative to a target.

new Actions(driver)

    .moveToElement(source)

    .clickAndHold()

    .moveToElement(target, 20, 20)

    .release()

    .perform();


45. Drag and Drop with Target Offset

Target offsets can be useful when a drop zone responds only to a particular area of the target element.

new Actions(driver)

    .clickAndHold(source)

    .moveToElement(target, 30, 10)

    .release()

    .perform();


46. Drag and Drop on Custom UI Controls

Modern web applications often use custom controls built with HTML, CSS, JavaScript, and frontend frameworks. Selenium can interact with these components when their drag-and-drop behavior responds correctly to WebDriver pointer actions.

WebElement source = driver.findElement(

    By.cssSelector(".custom-draggable")

);

 

WebElement target = driver.findElement(

    By.cssSelector(".custom-droppable")

);

 

new Actions(driver)

    .dragAndDrop(source, target)

    .perform();


47. Drag and Drop JavaScript Events

Web applications may implement drag-and-drop behavior using JavaScript events such as dragstart, dragover, and drop.

<div id="source" draggable="true">

    Drag Me

</div>

 

<div id="target">

    Drop Here

</div>


48. HTML5 Drag and Drop

HTML5 drag-and-drop components can sometimes behave differently from simple mouse-based components. The implementation of the web application determines whether the standard Actions sequence works correctly.

WebElement source = driver.findElement(

    By.id("source")

);

 

WebElement target = driver.findElement(

    By.id("target")

);

 

new Actions(driver)

    .dragAndDrop(source, target)

    .perform();


49. HTML5 Drag and Drop Troubleshooting

If a standard Actions drag-and-drop operation does not produce the expected result, investigate the application's event handling before choosing an alternative approach.

  • Inspect the HTML structure.
  • Check whether the source has draggable behavior.
  • Check the target drop-zone implementation.
  • Verify that the target is visible.
  • Try a manual Actions sequence.
  • Check browser-specific behavior.
  • Validate the result rather than only the mouse movement.


50. Drag and Drop Followed by Alert Handling

new Actions(driver)

    .dragAndDrop(source, target)

    .perform();

 

WebDriverWait wait =

    new WebDriverWait(driver, Duration.ofSeconds(10));

 

Alert alert = wait.until(

    ExpectedConditions.alertIsPresent()

);

 

System.out.println(alert.getText());

alert.accept();


51. Drag and Drop Followed by Page Navigation

new Actions(driver)

    .dragAndDrop(source, target)

    .perform();

 

WebDriverWait wait =

    new WebDriverWait(driver, Duration.ofSeconds(10));

 

wait.until(

    ExpectedConditions.urlContains("success")

);

 

System.out.println(driver.getCurrentUrl());


52. Drag and Drop and Verify URL

new Actions(driver)

    .dragAndDrop(source, target)

    .perform();

 

Assert.assertTrue(

    driver.getCurrentUrl().contains("success"),

    "Expected page was not opened"

);


53. Drag and Drop and Verify Text

new Actions(driver)

    .dragAndDrop(source, target)

    .perform();

 

WebElement message = driver.findElement(

    By.id("successMessage")

);

 

Assert.assertEquals(

    message.getText(),

    "Item moved successfully"

);


54. Drag and Drop and Verify Visibility

new Actions(driver)

    .dragAndDrop(source, target)

    .perform();

 

WebElement panel = new WebDriverWait(

    driver,

    Duration.ofSeconds(10)

).until(

    ExpectedConditions.visibilityOfElementLocated(

        By.id("resultPanel")

    )

);

 

Assert.assertTrue(panel.isDisplayed());


55. Drag and Drop with Scrolling

If the source or target is outside the visible viewport, scrolling can help bring the element into view before interaction.

WebElement target = driver.findElement(

    By.id("target")

);

 

((JavascriptExecutor) driver).executeScript(

    "arguments[0].scrollIntoView({block:'center'});",

    target

);

 

new Actions(driver)

    .dragAndDrop(source, target)

    .perform();


56. Required JavaScript Executor Import

import org.openqa.selenium.JavascriptExecutor;


57. Drag and Drop Inside an iframe

If the source and target elements exist inside an iframe, Selenium must switch into the iframe before locating and interacting with those elements.

WebElement frame = driver.findElement(

    By.id("dragFrame")

);

 

driver.switchTo().frame(frame);

 

WebElement source = driver.findElement(

    By.id("source")

);

 

WebElement target = driver.findElement(

    By.id("target")

);

 

new Actions(driver)

    .dragAndDrop(source, target)

    .perform();

 

driver.switchTo().defaultContent();


58. Drag and Drop in Nested Frames

driver.switchTo().frame("outerFrame");

driver.switchTo().frame("innerFrame");

 

WebElement source = driver.findElement(

    By.id("source")

);

 

WebElement target = driver.findElement(

    By.id("target")

);

 

new Actions(driver)

    .dragAndDrop(source, target)

    .perform();

 

driver.switchTo().defaultContent();


59. Drag and Drop in a New Window

If a drag-and-drop operation causes another browser window or tab to open, switch to the appropriate window before continuing with further validation.

String parent = driver.getWindowHandle();

 

new Actions(driver)

    .dragAndDrop(source, target)

    .perform();

 

for (String handle : driver.getWindowHandles()) {

    if (!handle.equals(parent)) {

        driver.switchTo().window(handle);

        break;

    }

}


60. Drag and Drop and Multiple Windows

String parentWindow = driver.getWindowHandle();

 

new Actions(driver)

    .dragAndDrop(source, target)

    .perform();

 

for (String handle : driver.getWindowHandles()) {

    if (!handle.equals(parentWindow)) {

        driver.switchTo().window(handle);

 

        System.out.println(

            driver.getTitle()

        );

    }

}


61. Drag and Drop Exception Handling

Automation frameworks should handle expected Selenium exceptions appropriately and provide useful logs.

try {

 

    WebElement source = driver.findElement(

        By.id("source")

    );

 

    WebElement target = driver.findElement(

        By.id("target")

    );

 

    new Actions(driver)

        .dragAndDrop(source, target)

        .perform();

 

} catch (Exception e) {

 

    System.out.println(

        "Drag and drop failed: " + e.getMessage()

    );

}


62. ElementNotInteractableException

This exception can occur when the source or target element cannot currently be interacted with.

Possible reasons include:

  • Element is hidden.
  • Element is disabled.
  • Element is outside the required UI state.
  • Another element is covering it.
  • Application state is not ready.


63. ElementClickInterceptedException

An overlay, popup, tooltip, or another element may interfere with the mouse interaction.

Useful troubleshooting steps include:

  • Wait for overlays to disappear.
  • Scroll the elements into view.
  • Check the source and target visibility.
  • Use stable locators.
  • Wait for the required application state.


64. StaleElementReferenceException

A stale element exception can occur when the DOM changes after the source or target was located.

A common solution is to locate the elements again after the DOM update.

WebElement source = wait.until(

    ExpectedConditions.refreshed(

        ExpectedConditions.elementToBeClickable(

            By.id("source")

        )

    )

);

 

WebElement target = wait.until(

    ExpectedConditions.refreshed(

        ExpectedConditions.visibilityOfElementLocated(

            By.id("target")

        )

    )

);

 

new Actions(driver)

    .dragAndDrop(source, target)

    .perform();


65. Element Not Visible Problem

If an element is not visible, check:

  • Whether the correct locator is used.
  • Whether the element is displayed.
  • Whether the parent component is collapsed.
  • Whether an iframe switch is required.
  • Whether an overlay is covering the element.
  • Whether the application has finished loading.


66. Drag and Drop on Hidden Elements

A hidden element should not normally be treated as an ordinary user-interaction target. Instead, make the required UI state visible and interact with the actual visible source or target.


67. Drag and Drop on Disabled Elements

A disabled control may not accept a drag-and-drop operation. Selenium should verify the application behavior instead of forcing an artificial interaction.

WebElement target = driver.findElement(

    By.id("dropTarget")

);

 

Assert.assertFalse(

    target.isEnabled(),

    "Target should be disabled"

);


68. Drag and Drop with Stable Locators

Stable locators make drag-and-drop tests more reliable.

  • Prefer unique IDs.
  • Use meaningful data attributes where available.
  • Use stable CSS selectors.
  • Use relative XPath when appropriate.
  • Avoid fragile absolute XPath.


69. Good XPath Example

By.xpath("//div[@data-item='task-1001']")


70. Avoid Fragile XPath

Avoid locators that depend heavily on changing DOM indexes.

//div[3]/div[2]/table/tr[4]/td[2]/div

Prefer a meaningful attribute or relationship-based locator.


71. Drag and Drop Test Scenario

Consider a task-management application containing a Kanban board. A user drags a task from the To Do column to the In Progress column.

  1. Open the task-management application.
  2. Login with valid credentials.
  3. Navigate to the Kanban board.
  4. Locate the required task.
  5. Locate the destination column.
  6. Drag the task to the destination.
  7. Wait for the UI update.
  8. Verify that the task appears in the destination column.
  9. Capture evidence if required.
  10. Close the browser.


72. Kanban Drag and Drop Example

WebDriverWait wait =

    new WebDriverWait(driver, Duration.ofSeconds(10));

 

WebElement task = wait.until(

    ExpectedConditions.elementToBeClickable(

        By.xpath("//div[@data-task='TASK1001']")

    )

);

 

WebElement inProgress = wait.until(

    ExpectedConditions.visibilityOfElementLocated(

        By.id("inProgress")

    )

);

 

new Actions(driver)

    .dragAndDrop(task, inProgress)

    .perform();

 

WebElement movedTask = wait.until(

    ExpectedConditions.visibilityOfElementLocated(

        By.xpath("//div[@data-task='TASK1001']")

    )

);

 

Assert.assertTrue(

    movedTask.isDisplayed(),

    "Task was not displayed after drag and drop"

);


73. E-Commerce Drag and Drop Scenario

An e-commerce application may allow a user to drag a product into a comparison area or shopping cart.

WebElement product = driver.findElement(

    By.cssSelector(".product-card")

);

 

WebElement cart = driver.findElement(

    By.id("cart")

);

 

new Actions(driver)

    .dragAndDrop(product, cart)

    .perform();


74. File Manager Drag and Drop Scenario

A web-based file manager may allow users to move files between folders using drag and drop.

WebElement file = driver.findElement(

    By.cssSelector(".file-item")

);

 

WebElement folder = driver.findElement(

    By.cssSelector(".destination-folder")

);

 

new Actions(driver)

    .dragAndDrop(file, folder)

    .perform();


75. Dashboard Drag and Drop Scenario

A dashboard may allow users to rearrange widgets by dragging one widget to another location.

WebElement widget = driver.findElement(

    By.id("revenueWidget")

);

 

WebElement targetArea = driver.findElement(

    By.id("dashboardDropZone")

);

 

new Actions(driver)

    .dragAndDrop(widget, targetArea)

    .perform();


76. Sample Test Case

Test Case IDScenarioExpected Result
TC-DRAGDROP-001Drag valid task to target columnTask moves successfully
TC-DRAGDROP-002Drag product to cartProduct is added to cart
TC-DRAGDROP-003Drag item to disabled targetItem is not moved
TC-DRAGDROP-004Drag dynamic elementElement is located after loading and operation succeeds


77. Drag and Drop Test Case Template

Test Case ID: TC-DRAGDROP-001

Title: Verify drag and drop functionality

Precondition: User is logged in

Steps:

1. Navigate to the required page

2. Locate the source element

3. Locate the target element

4. Perform drag and drop

5. Wait for expected result

6. Validate the result

 

Expected Result:

The source element should be moved to the

specified destination successfully.


78. Drag and Drop with Screenshot on Failure

try {

 

    WebElement source = driver.findElement(

        By.id("source")

    );

 

    WebElement target = driver.findElement(

        By.id("target")

    );

 

    new Actions(driver)

        .dragAndDrop(source, target)

        .perform();

 

} catch (Exception e) {

 

    File screenshot = ((TakesScreenshot) driver)

        .getScreenshotAs(OutputType.FILE);

 

    System.out.println(

        "Drag and drop failed: " + e.getMessage()

    );

}


79. Screenshot Imports

import org.openqa.selenium.OutputType;

import org.openqa.selenium.TakesScreenshot;

import java.io.File;


80. Logging Drag and Drop Actions

Logging helps identify the source, target, and stage at which a drag-and-drop operation failed.

System.out.println(

    "Performing drag and drop"

);

 

new Actions(driver)

    .dragAndDrop(source, target)

    .perform();

 

System.out.println(

    "Drag and drop completed"

);


81. Drag and Drop in Automation Framework

In a professional framework, drag-and-drop logic should be reusable rather than duplicated across every test.

  • Page objects should contain page-specific elements.
  • Action utilities should contain reusable interactions.
  • Wait utilities should contain synchronization logic.
  • Test classes should focus on test scenarios.
  • Reporting should capture failures.


82. Recommended Framework Structure

src

├── main

│   └── java

│       ├── pages

│       ├── utilities

│       ├── waits

│       └── base

└── test

    └── java

        ├── tests

        └── testdata


83. Drag and Drop Utility with Wait

public void dragAndDrop(By sourceLocator, By targetLocator) {

 

    WebDriverWait wait =

        new WebDriverWait(driver, Duration.ofSeconds(10));

 

    WebElement source = wait.until(

        ExpectedConditions.elementToBeClickable(

            sourceLocator

        )

    );

 

    WebElement target = wait.until(

        ExpectedConditions.visibilityOfElementLocated(

            targetLocator

        )

    );

 

    new Actions(driver)

        .dragAndDrop(source, target)

        .perform();

}


84. Using the Utility

dragAndDrop(

    By.id("source"),

    By.id("target")

);


85. Best Practices for Drag and Drop

  • Use the Actions class for mouse-based drag-and-drop interactions.
  • Prefer stable source and target locators.
  • Use explicit waits for dynamic applications.
  • Verify the result after the interaction.
  • Use manual Actions when direct dragAndDrop does not match the application's behavior.
  • Avoid unnecessary hard-coded sleeps.
  • Handle iframes correctly.
  • Capture screenshots for important failures.
  • Keep page-specific locators inside page objects.
  • Use meaningful test case names.
  • Prefer element-based interaction over fixed coordinates.


86. Common Mistakes

  • Using click() when drag and drop is required.
  • Trying to drag a hidden element.
  • Using unstable XPath expressions.
  • Ignoring dynamic loading.
  • Not switching into an iframe.
  • Ignoring overlays and popups.
  • Using unnecessary JavaScript instead of normal user interaction.
  • Not validating the final location of the element.
  • Duplicating Actions code across many tests.
  • Using long hard-coded sleeps.
  • Relying heavily on screen coordinates.


87. Drag and Drop vs JavaScript

AspectActions Drag and DropJavaScript
User-like interactionYesDepends on implementation
Mouse movementSupportedNot a direct mouse interaction
Preferred for normal UI testingYesUsually fallback
MaintainabilityGenerally betterDepends on use case


88. Why Actions is Preferred?

The Actions API represents advanced user interactions and is appropriate when a test needs to simulate mouse behavior such as drag and drop, double click, hover, click and hold, and keyboard combinations.


89. Drag and Drop and Accessibility

When automating drag-and-drop functionality, testers should also consider whether the application provides an accessible alternative. Important workflows should not depend exclusively on mouse gestures when an equivalent keyboard or other accessible interaction is available.


90. Drag and Drop on Responsive Applications

Responsive layouts may change element positions and dimensions across viewport sizes. Prefer element-based interaction rather than fixed coordinate-based automation.

WebElement source = driver.findElement(

    By.cssSelector(".responsive-source")

);

 

WebElement target = driver.findElement(

    By.cssSelector(".responsive-target")

);

 

new Actions(driver)

    .dragAndDrop(source, target)

    .perform();


91. Drag and Drop in Cross-Browser Testing

When executing automation across multiple browsers, verify that the application responds consistently to the drag-and-drop interaction.

BrowserTest
ChromeDrag and drop behavior
FirefoxDrag and drop behavior
EdgeDrag and drop behavior


92. Drag and Drop in Parallel Testing

When tests run in parallel, each test should use an isolated driver instance and independent test data wherever required. This prevents one test from changing the source or target state used by another test.


93. Drag and Drop and Test Data

For data-driven tests, the source item and destination can be supplied from test data rather than hard-coded values.

String taskId = "TASK1001";

String targetColumn = "inProgress";

 

WebElement source = driver.findElement(

    By.xpath("//div[@data-task='" + taskId + "']")

);

 

WebElement target = driver.findElement(

    By.id(targetColumn)

);

 

new Actions(driver)

    .dragAndDrop(source, target)

    .perform();


94. Data-Driven Drag and Drop Testing

Task IDDestinationExpected Action
TASK1001In ProgressTask moves successfully
TASK1002CompletedTask moves successfully
TASK1003ReviewTask moves successfully


95. Interview Question: What is Drag and Drop in Selenium?

Drag and Drop is an advanced mouse interaction used to move a web element from one location to another. Selenium Java provides the dragAndDrop() method through the Actions class.


96. Interview Question: How do You Perform Drag and Drop?

Actions actions = new Actions(driver);

actions.dragAndDrop(source, target).perform();


97. Interview Question: Which Class is Used for Drag and Drop?

The org.openqa.selenium.interactions.Actions class is commonly used to perform drag-and-drop and other advanced user interactions.


98. Interview Question: What if dragAndDrop() Does Not Work?

For complex custom components, a manual Actions sequence can be attempted.

new Actions(driver)

    .moveToElement(source)

    .clickAndHold()

    .moveToElement(target)

    .release()

    .perform();


99. Interview Question: Why Use perform()?

The perform() method executes the interaction sequence built using the Actions API.

new Actions(driver)

    .dragAndDrop(source, target)

    .perform();


100. Quick Revision

  • Drag and Drop moves an element from one location to another.
  • Selenium's Actions class supports drag-and-drop interactions.
  • Use dragAndDrop(source, target) for standard interactions.
  • Use clickAndHold(), moveToElement(), and release() for manual control.
  • Call perform() to execute the action.
  • Use explicit waits for dynamic elements.
  • Use stable source and target locators.
  • Switch into iframes before interacting with their elements.
  • Validate the final application state after the operation.
  • Use reusable utilities in automation frameworks.


101. Drag and Drop Checklist

  • Source element identified correctly.
  • Target element identified correctly.
  • Stable locators used.
  • Source is visible.
  • Target is visible.
  • Elements are interactable.
  • Required iframe handled.
  • Required wait implemented.
  • Actions object created.
  • Drag and drop executed.
  • Expected result validated.
  • Failure evidence captured where required.
  • Test data isolated.
  • Reusable framework utility used where appropriate.


102. Practical Mini Project

Project: Kanban Task Drag and Drop Automation

Automate a task-management application where a task can be dragged from the To Do column into the In Progress column.

  1. Launch the browser.
  2. Open the task-management application.
  3. Login with valid credentials.
  4. Navigate to the Kanban board.
  5. Locate the required task using a stable locator.
  6. Locate the destination column.
  7. Wait until both elements are ready.
  8. Perform drag and drop using Actions.
  9. Wait for the board to update.
  10. Validate that the task appears in the destination column.
  11. Capture a screenshot if the test fails.
  12. Generate the test report.
  13. Close the browser.

@Test

public void verifyTaskDragAndDrop() {

 

    WebDriverWait wait =

        new WebDriverWait(driver, Duration.ofSeconds(10));

 

    WebElement task = wait.until(

        ExpectedConditions.elementToBeClickable(

            By.cssSelector("div[data-task='TASK1001']")

        )

    );

 

    WebElement inProgress = wait.until(

        ExpectedConditions.visibilityOfElementLocated(

            By.id("inProgress")

        )

    );

 

    new Actions(driver)

        .dragAndDrop(task, inProgress)

        .perform();

 

    WebElement movedTask = wait.until(

        ExpectedConditions.visibilityOfElementLocated(

            By.cssSelector("div[data-task='TASK1001']")

        )

    );

 

    Assert.assertTrue(

        movedTask.isDisplayed(),

        "Task was not displayed after drag and drop"

    );

}


103. Conclusion

Drag and Drop is an important mouse interaction in Selenium WebDriver automation. Selenium Java provides the Actions class and its dragAndDrop() method to automate interfaces that depend on moving elements from one location to another.

A reliable drag-and-drop test should use stable source and target locators, appropriate waits, correct frame or window handling, reusable framework utilities, and assertions that verify the expected application behavior.

For complex custom interfaces, the manual sequence of clickAndHold(), moveToElement(), and release() can provide greater control than the direct dragAndDrop() method.

Drag-and-drop automation is especially useful for CRM systems, e-commerce applications, Kanban boards, dashboards, file-management interfaces, sortable lists, workflow applications, and other web applications where mouse movement is part of the user workflow.

Recommended Selenium Learning Resources:

Selenium Training Course | Register for Course Demo

whatsapp