How to Perform Drag and Drop in Selenium
How to Perform Drag and Drop in Selenium – 2026
Drag and drop lets users move elements within a web application, creating smooth, interactive workflows. In testing, automating this ensures elements can be repositioned or uploaded as intended. Selenium WebDriver enables this by simulating real user actions like click, hold, and release.
Automation can be tricky since browser behaviors vary and HTML5 elements need advanced handling. Selenium’s Actions class and JavaScript execution help manage both standard and complex drag-and-drop cases.
This article covers how to perform drag and drop in Selenium, handle HTML5 cases, fix issues, and follow best practices.
Understanding Drag and Drop in Selenium Automation
Drag and drop in Selenium automates the process of selecting an element, moving it to a target area, and releasing it. This approach helps validate interactive components such as file uploads, sortable lists, sliders, and other UI elements that rely on user gestures.
Selenium uses the Actions class to perform this operation. It simulates a sequence of user actions like clicking, holding, moving, and releasing the mouse to replicate real-world behavior. This method works effectively for standard web elements but may require adjustments when dealing with advanced or script-driven interfaces.
Choosing the correct approach, whether through Actions, JavaScript, or a combination of both, ensures consistent and accurate drag-and-drop automation across browsers and user environments.
Performing Drag and Drop in Selenium
Selenium provides several ways to automate drag and drop actions, depending on how the web elements are implemented. The most common method is through the Actions class, which replicates user gestures step by step. Before implementing, ensure both the source and target elements are identifiable through reliable locators such as ID, name, CSS selector, or XPath.
Step 1: Set up WebDriver
Initialize the WebDriver instance and navigate to the target web page.
Step 2: Locate elements
Identify both the source element (to be dragged) and the destination element (where it needs to be dropped).
Step 3: Create an Actions object
Instantiate the Actions class by passing the WebDriver instance.
Step 4: Perform drag and drop
Use clickAndHold(source), moveToElement(target), and release() methods or the dragAndDrop(source, target) shortcut.
Step 5: Execute the action
Call the perform() method to complete the action sequence.
This process enables precise automation of drag and drop behavior and helps verify that the web application responds correctly to user interactions across different browsers.
Drag and Drop vs Action Class Build: Key Differences
Selenium offers two ways to execute complex user actions such as drag and drop. The first is by directly calling the perform() method after chaining multiple actions, and the second is by using the build() method before execution. Both approaches achieve similar results, but they differ in how they handle the sequence and timing of actions.
When perform() is called directly, Selenium executes the defined actions immediately in sequence. This approach is straightforward and suitable for simple drag and drop operations where the sequence is short. On the other hand, using build() allows the tester to queue multiple actions first and execute them together later.
This is especially useful when the test involves several combined gestures or when more precise synchronization is required.
Choosing between these approaches depends on the complexity of the interaction. For basic drag and drop, calling perform() directly is sufficient. For advanced workflows involving multiple user gestures or dependent actions, using build() followed by perform() ensures better control and reliability.
Handling HTML5 Drag and Drop in Selenium
HTML5 drag and drop elements rely on JavaScript-driven events that the standard Selenium Actions class cannot fully replicate. Since Actions only simulates mouse movements, it often fails to trigger events like dragstart, dragover, and drop correctly. To automate such cases, JavaScript execution or custom event simulation is required.
Ways to handle HTML5 drag and drop in Selenium:
- Use JavaScript Executor: Inject custom JavaScript code to manually fire dragstart, dragenter, dragover, and drop events between the source and target elements.
- Leverage external scripts: Include open-source helper scripts like the HTML5 drag and drop simulator from GitHub to handle event dispatching more reliably.
- Simulate offsets: When JavaScript injection is not possible, use clickAndHold, moveByOffset, and release methods to simulate dragging within specific coordinates.
- Combine Actions with JavaScript: For complex UI components, combine both approaches to ensure accurate event propagation and browser compatibility.
Example: Automating a Drag and Drop Test Case
The following example demonstrates how to perform a basic drag and drop action in Selenium using the Actions class. This test moves an element from one location to another and verifies that the drop operation is successful.
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) {
// Set up WebDriver
WebDriver driver = new ChromeDriver();
driver.get("https://example.com/drag-and-drop");
// Locate source and target elements
WebElement source = driver.findElement(By.id("draggable"));
WebElement target = driver.findElement(By.id("droppable"));
// Perform drag and drop
Actions action = new Actions(driver);
action.dragAndDrop(source, target).perform();
// Verify result
String text = target.getText();
if (text.contains("Dropped")) {
System.out.println("Drag and drop successful");
} else {
System.out.println("Drag and drop failed");
}
// Close the browser
driver.quit();
}
}This script launches a browser, identifies the draggable and droppable elements, and uses the dragAndDrop() method to perform the action. The test then validates whether the text of the target element changes after the drop, confirming that the drag and drop operation worked as intended.
Troubleshooting Selenium Drag and Drop Failures
Drag and drop automation can fail for several reasons, especially across different browsers or when dealing with dynamic elements. Identifying the cause helps ensure reliable execution and consistent results.
Common reasons for drag and drop failures and how to fix them:
- Incompatible element locators: Ensure that the source and target elements are visible and interactable. Use explicit waits like WebDriverWait to handle delayed rendering or dynamic loading.
- HTML5-based events: The default Actions API may not trigger HTML5-specific JavaScript events. Use JavaScript execution or helper scripts to simulate these events.
- Hidden or overlapping elements: Some UI designs place invisible layers over draggable items. Use JavaScript to scroll into view or remove overlays before performing the action.
- Incorrect offsets: If using coordinate-based methods like moveByOffset, verify the offset values through developer tools to ensure accurate positioning.
- Browser-specific behavior: Some browsers interpret mouse events differently. Always test across major browsers to detect inconsistencies early.
Best Practices for Selenium Drag and Drop Automation
Ensuring accuracy and stability in drag and drop automation requires careful implementation. Following best practices helps reduce flakiness and improves test reliability across browsers and environments.
Key best practices for stable drag and drop automation:
- Ensure visibility and stability before interaction: Always confirm that both source and target elements are visible, interactable, and stable before the drag begins. Use WebDriverWait with conditions like elementToBeClickable() or visibilityOfElementLocated(). If the DOM changes frequently, re-locate the elements immediately before performing the action to avoid stale element exceptions.
- Avoid relying solely on dragAndDrop(): The built-in dragAndDrop() method often fails on HTML5 or script-driven elements because it does not fire all JavaScript drag events. Instead, use a step-by-step sequence with clickAndHold(), moveToElement(), release(), or inject JavaScript that triggers native drag events for more consistent behavior.
- Incorporate JavaScript event validation: After the drop action, verify that JavaScript events like dragstart, dragenter, and drop were triggered. You can validate this by checking for expected DOM updates, such as class name changes, data attribute updates, or success messages that indicate a completed drop.
- Simulate realistic user speed and motion: Some UI libraries detect drag and drop based on timing or mouse movement patterns. Add small pauses using pause(Duration.ofMillis(500)) or move the element gradually across offsets rather than jumping directly from source to target. This creates more human-like behavior and prevents false negatives.
- Handle scrolling and hidden targets: Many drop zones appear only after scrolling or hovering. Use JavaScript’s scrollIntoView() or Actions’ moveToElement() to bring elements into view before dragging. If elements are hidden behind overlays, remove them temporarily through JavaScript to enable smooth interaction.
- Test on real browsers and devices: Browser simulation often skips subtle event-handling differences that affect drag and drop reliability. Running these tests on real browsers and devices ensures that the underlying JavaScript event propagation, timing, and UI rendering behave as they do in actual user environments.
Why Run Selenium Drag and Drop Tests on Real Devices?
Automating drag and drop tests only on emulators or virtual environments does not reflect real-world behavior. Actual users interact on physical devices with different browsers, operating systems, screen sizes, and input types, which can affect how elements respond to drag and drop actions.
Running tests on real devices ensures that these variations are accurately captured and that UI behavior remains consistent for every user scenario.
Cloud-based testing tools enable teams to execute Selenium tests on thousands of real desktop and mobile devices directly from the cloud. This helps validate drag and drop interactions under real conditions while eliminating the need for maintaining an in-house device lab.
Key advantages of running drag and drop tests on cloud-based testing tools:
- Real device coverage: Access to real browsers and devices, including physical Android and iOS devices, to test actual user interactions.
- Accurate simulation: Validate touch gestures, mouse drags, and UI responsiveness in real environments where timing and rendering differ from emulators.
- Debugging support: Capture videos, screenshots, and logs for every test session to identify and fix drag and drop failures quickly.
- Cross-browser consistency: Ensure that drag and drop workflows perform the same way on Chrome, Safari, Edge, and Firefox across multiple OS versions.
- Scalability: Run parallel Selenium tests in the cloud to reduce execution time while maintaining full test accuracy across devices.
Conclusion
Automating drag and drop in Selenium helps validate real user interactions and ensures UI elements behave as expected across different browsers. By combining Actions, JavaScript execution, and best practices, testers can create stable, cross-browser automation that accurately replicates complex user gestures.
Related Articles
Automating File Uploads in Selenium in 2026
Discover how to automate file uploads in Selenium, including best practices, methods like sendKeys()...
Selenium and Java in 2026
Understand the core benefits of using Selenium with Java for automation testing. Learn how to set up...
Bypassing Cloudflare Challenges in 2026 using Selenium
Explore effective methods to bypass Cloudflare using Selenium, Puppeteer, and Playwright with ethica...