How to Drag and Drop in Selenium (Example)

โšก Smart Summary

Drag and Drop in Selenium WebDriver enables automated simulation of mouse-based interactions that move a source element and release it on a defined target. The Actions class powers these gestures through dragAndDrop and dragAndDropBy methods for precise, repeatable browser automation.

  • ๐ŸŽ“ Use the Actions class to build keyboard and mouse gestures, then call build() and perform() to execute them on the page.
  • ๐ŸŒŸ Choose dragAndDrop(source, target) when you have both elements, and dragAndDropBy(source, xOffset, yOffset) when you need pixel-level precision.
  • ๐Ÿš€ Always wait for the source and target elements to be present before invoking the drag operation to avoid flaky tests.
  • ๐ŸŽ–๏ธ Verify the drop visually or by asserting attribute changes on the target so the test confirms real interaction, not just a queued action.
  • ๐Ÿ† AI-assisted locators heal broken XPaths after UI updates, reducing maintenance for drag-and-drop suites running in CI pipelines.

Drag and Drop in Selenium

What is Drag and Drop in Selenium?

Drag and Drop in Selenium is an automated interaction that simulates clicking and holding a source element, moving it across the page, and releasing it on a target location. It is widely used to test modern web applications that rely on drag-and-drop interfaces, such as file uploaders, kanban boards, shopping carts, and dashboard builders.

In Selenium WebDriver, drag and drop is performed through the Actions class, which provides specialized methods to chain mouse gestures and execute them as a single composite action.

Drag and Drop in Selenium

The Actions class exposes two primary methods for drag-and-drop automation:

Syntax:

Actions act = new Actions(driver);
//for drag and drop directly on an element
act.dragAndDrop(Source, Destination).build().perform();

//for drag and drop with pixel offsets
act.dragAndDropBy(WebElement Source, int xOffset, int yOffset).build().perform();

Here, dragAndDrop() takes the source and destination WebElements, while dragAndDropBy() takes the source element and the x/y pixel offsets to move it by.

How to Drag and Drop in Selenium

The following three scenarios demonstrate practical drag-and-drop automation on the Guru99 demo page https://demo.guru99.com/test/drag_drop.html. The goal is to move the BANK debit element into the Account debit side area so that the amount of $5000 is correctly accounted as a debit transaction.

Scenario 1: Drag and Drop using the dragAndDrop method

In this scenario, the source element (BANK) is dragged onto the destination (Account debit side) using the dragAndDrop(source, target) method, which accepts the source and destination WebElements directly.

Drag and Drop Scenario 1 setup

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) {
        System.setProperty("webdriver.chrome.driver", "G:\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("https://demo.guru99.com/test/drag_drop.html");

        // Locate the source (BANK) element
        WebElement Source = driver.findElement(By.xpath("//*[@id='credit2']/a"));
        // Locate the target (Account debit side) element
        WebElement Dest = driver.findElement(By.xpath("//*[@id='bank']/li"));

        // Create the Actions instance
        Actions act = new Actions(driver);
        // Perform drag and drop
        act.dragAndDrop(Source, Dest).build().perform();
    }
}

After the script runs, the BANK tile moves into the Account debit area and the $5000 amount is registered as a debit.

Eclipse running the drag and drop script

The visual result on the demo page looks like this:

Drag and Drop output animation

Scenario 2: Drag and Drop using the dragAndDropBy method

The dragAndDropBy(source, xOffset, yOffset) method offers pixel-level precision. Instead of dropping on a target element, it moves the source by a specified number of pixels along the X and Y axes.

To determine the offset, hover over the destination area in your browser and read the pixel coordinates with a tool like the inspector ruler or a screen-coordinates extension.

Identifying pixel offsets for dragAndDropBy

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 DragAndDropByExample {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "G:\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("https://demo.guru99.com/test/drag_drop.html");

        // Locate the source (BANK) element
        WebElement Source = driver.findElement(By.xpath("//*[@id='credit2']/a"));

        // Create the Actions instance
        Actions act = new Actions(driver);
        // Drag the source by 400 pixels right and 0 pixels down
        act.dragAndDropBy(Source, 400, 0).build().perform();
    }
}

The script moves the BANK tile by the supplied offset and drops it on the Account debit side, producing the same financial result as Scenario 1.

Scenario 3: Drag, drop, and verify multiple elements

This scenario chains multiple drag-and-drop operations and verifies the result by asserting the final amount on the target. Several source elements (BANK, SALES, 5000, 500) are moved into their respective debit and credit zones, and the script confirms the totals match the expected balance.

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 DragAndDropMultiple {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "G:\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("https://demo.guru99.com/test/drag_drop.html");

        // Locate sources
        WebElement srcBank = driver.findElement(By.xpath("//*[@id='credit2']/a"));
        WebElement srcSales = driver.findElement(By.xpath("//*[@id='credit1']/a"));
        WebElement src5000 = driver.findElement(By.xpath("//*[@id='fourth']/a"));
        WebElement src500 = driver.findElement(By.xpath("//*[@id='fourth']/a"));

        // Locate targets
        WebElement debitSide = driver.findElement(By.xpath("//*[@id='bank']/li"));
        WebElement creditSide = driver.findElement(By.xpath("//*[@id='loan']/li"));
        WebElement amount7 = driver.findElement(By.xpath("//*[@id='amt7']/li"));
        WebElement amount8 = driver.findElement(By.xpath("//*[@id='amt8']/li"));

        Actions act = new Actions(driver);
        act.dragAndDrop(srcBank, debitSide).build().perform();
        act.dragAndDrop(srcSales, creditSide).build().perform();
        act.dragAndDrop(src5000, amount7).build().perform();
        act.dragAndDrop(src500, amount8).build().perform();

        // Verify the displayed total
        String total = driver.findElement(By.xpath("//*[@id='totamt']")).getText();
        if (total.equals("5500")) {
            System.out.println("Test Passed: total matches expected 5500");
        } else {
            System.out.println("Test Failed: actual total " + total);
        }
    }
}

This pattern demonstrates how drag-and-drop can be combined with assertions to validate functional behaviour, not just visual movement.

Best Practices for Drag and Drop Automation

Drag-and-drop tests are among the most flaky scripts in a Selenium suite because they depend on precise mouse coordinates and DOM readiness. The following practices keep them reliable:

  • Wait for elements: Use WebDriverWait with ExpectedConditions.elementToBeClickable before invoking the drag.
  • Prefer dragAndDrop over JavaScript hacks: Native HTML5 drag events sometimes need a JavaScript fallback, but rely on the Actions API first.
  • Scroll the target into view: An off-screen destination causes silent failures. Use Actions.scrollToElement or a JavaScript scroll before dragging.
  • Verify the outcome: Always assert a measurable state change (text, attribute, count) after the drop instead of trusting the action ran.
  • Run on a stable resolution: Pixel-offset drags break if the viewport size differs from the one used to compute the offsets.

FAQs

Drag and drop in Selenium is an automated mouse gesture that picks up a source element and releases it on a target. It is performed through the Actions class using dragAndDrop or dragAndDropBy.

dragAndDrop accepts the source and destination WebElements. dragAndDropBy takes the source plus x and y pixel offsets, giving precise control when the destination is not a discrete element.

build() compiles the chained interactions into a single composite Action, and perform() executes it. Without perform(), the queued steps never run against the browser.

Many HTML5 sites use native drag events that the Actions API does not always trigger. In those cases, dispatch the dragstart, dragover, and drop events through executeScript as a JavaScript fallback.

Open browser DevTools, hover over the destination, and read the element’s getBoundingClientRect values. Subtract the source position from the target position to get the x and y offsets in pixels.

Yes. Wrap the source and target lookups in WebDriverWait with ExpectedConditions.elementToBeClickable so the drag only runs after both elements are interactive, reducing flakiness in CI runs.

AI tools provide self-healing locators that adapt when XPaths change, and recommend stable selectors for source and target elements. This cuts maintenance for drag-and-drop suites running across releases.

Yes. AI coding assistants turn a plain-English scenario such as “drag BANK to the debit side and assert the total” into a complete Actions chain with dragAndDrop, build, perform, and a verification step.

Summarize this post with: