Contents

    Guides

    How to Drag and Drop an Element Using Selenium WebDriver

    Published on

    October 29, 2025
    How to Drag and Drop an Element Using Selenium WebDriver

    Drag and drop is a common web interaction where a user clicks an element, holds it, and moves it to a target. Automating this in Selenium WebDriver lets testers verify workflows involving sliders, lists, file uploads, and interactive dashboards. Accurate automation ensures the UI behaves correctly under test conditions.

    Selenium provides methods to simulate these actions using the Actions class, which can click, hold, move, and release elements like a real user. HTML5 drag and drop often needs a more advanced approach because standard methods may fail across browsers.

    This article covers how to perform drag and drop in Selenium WebDriver, including techniques, common issues, and best practices.

    What is Drag and Drop in Selenium?

    Drag and drop in Selenium refers to automating the movement of a web element from one location to another on a web page. It mimics the user action of clicking an element, holding it, moving it, and releasing it at a target position. This interaction is widely used in applications with interactive lists, dashboards, file uploads, sliders, and game interfaces.

    Selenium WebDriver supports this through methods that replicate user gestures. The most common approach uses the Actions class to perform click-and-hold, move, and release sequences. For HTML5 elements, additional techniques such as JavaScript execution may be required because native drag-and-drop events may not fire correctly across all browsers.

    Use Cases of Drag and Drop in Selenium

    Drag and drop interactions are common in modern web applications, but automating them is not always straightforward. These interactions often involve dynamic element positions, overlapping layers, or custom JavaScript events. Below are real-world scenarios where drag and drop automation is essential, with deeper technical context:

    • Interactive Dashboards: Users can rearrange widgets or panels. Automation must verify not just the movement but also that the new positions persist in the DOM and update the underlying state or database. For example, a dashboard might use a grid layout library that updates positions via JavaScript events, which standard drag-and-drop methods may not trigger reliably.
    • File Uploads: Many web applications support drag-and-drop file uploads. Automated testing must simulate the drop event correctly and verify that client-side validation, progress indicators, and server upload handling respond as expected.
    • Sortable Lists: Dragging items to reorder a list requires checking both the visual change and the order reflected in backend data. Complex lists may use libraries that update positions asynchronously, requiring explicit waits in Selenium.
    • Sliders and Range Selectors: Moving sliders involves precise offset calculations. Automation should ensure that the element stops at the expected value, especially when the slider updates values dynamically via JavaScript on mouse events.
    • Workflow Builders and Kanban Boards: Tasks or cards in drag-and-drop workflows often trigger multiple event handlers, including validation, state changes, and notifications. Automated tests must confirm that all these actions execute correctly after the drop.

    How to Perform Drag and Drop in Selenium

    Performing drag and drop in Selenium involves simulating user interactions while ensuring the underlying events fire correctly. The challenge is that different web elements and frameworks handle drag-and-drop events differently. Standard approaches may fail with HTML5 elements or dynamically positioned items, so understanding the mechanics is crucial.

    There are three main approaches to performing drag and drop in Selenium:

    1. Using the Actions Class 

    Selenium’s Actions class can chain mouse events to replicate drag-and-drop behavior. For example, clickAndHold(source).moveToElement(target).release().perform() simulates picking up an element, moving it, and dropping it. This works for most standard web elements, but may fail if the target uses complex JavaScript event handling or custom drag-and-drop libraries.

    2. Using Offset Movements

    When elements cannot be dropped directly onto a target, moving by a calculated offset can help. moveByOffset(x, y) lets you drag an element a specific number of pixels. This is useful for sliders or elements whose drop targets are not recognized by moveToElement.

    3. Using JavaScript Execution

    For HTML5 or canvas-based drag-and-drop elements, standard Selenium actions may not trigger the necessary events. Executing JavaScript to manually dispatch dragstart, dragover, and drop events ensures the element behaves as expected. This method provides control over the sequence of events and is more reliable for advanced interactions.

    Note: Each method has trade-offs. The Actions class is simple but sometimes unreliable with custom front-end frameworks. Offset movements require precise calculations and may fail if layouts change. JavaScript execution is more complex but offers reliability for HTML5 and dynamic interfaces.

    Drag and Drop Using the Actions Class

    The Actions class in Selenium WebDriver provides a way to simulate complex user interactions, including drag-and-drop. It works by chaining low-level mouse actions like clickAndHold, moveToElement, and release to replicate real user behavior. This method is most effective for standard web elements but may fail with HTML5-based drag-and-drop implementations.

    Below is an example of using the Actions class in Java:

    // Locate source and target elements

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

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

    // Create an Actions object

    Actions actions = new Actions(driver);

    // Perform drag and drop

    actions.clickAndHold(source)

           .moveToElement(target)

           .release()

           .build()

           .perform();

    Key points to note:

    • Element visibility: Both source and target elements must be visible and interactable. Hidden or off-screen elements can cause the action to fail.
    • Browser differences: Some browsers may handle drag-and-drop differently, so cross-browser testing is essential.
    • Intermediate movements: Adding small moveByOffset steps can help if the drop target is small or dynamically positioned. For example:

    actions.clickAndHold(source)

         .moveByOffset(50, 0)

           .moveToElement(target)

           .release()

           .perform();

    • Chaining actions: The build() method compiles the sequence before execution, ensuring that all steps occur in order without interruption.

    Using the Actions class provides a straightforward way to automate standard drag-and-drop interactions while maintaining a sequence similar to a real user. It also allows adding extra steps like pauses or offsets to handle dynamic layouts.

    HTML5 Drag and Drop in Selenium (Advanced)

    HTML5 drag and drop introduces a challenge for Selenium automation. Standard Actions class methods often fail because they do not trigger the underlying JavaScript drag events (dragstart, dragover, drop) that HTML5 relies on. These events are handled by the browser’s internal event model, so Selenium’s simulated mouse actions may not be recognized by the page.

    To handle HTML5 drag and drop, testers typically use JavaScript execution to trigger the correct event sequence manually. This ensures that both the visual movement and event-based logic are validated. 

    Below is a practical example using JavaScript with Selenium WebDriver in Java:

    JavascriptExecutor js = (JavascriptExecutor) driver;

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

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

    String script = 

    "function triggerDragAndDrop(source, target) {" +

    "  const dataTransfer = new DataTransfer();" +

    "  const dragStartEvent = new DragEvent('dragstart', { dataTransfer });" +

    "  source.dispatchEvent(dragStartEvent);" +

    "  const dragOverEvent = new DragEvent('dragover', { dataTransfer });" +

    "  target.dispatchEvent(dragOverEvent);" +

    "  const dropEvent = new DragEvent('drop', { dataTransfer });" +

    "  target.dispatchEvent(dropEvent);" +

    "}" +

    "triggerDragAndDrop(arguments[0], arguments[1]);";

    js.executeScript(script, source, target);

    This approach directly fires the drag-and-drop events in the browser’s DOM, bypassing the limitations of Selenium’s native mouse simulation.

    Points to consider when using this method:

    • DataTransfer object: HTML5 drag events rely on the DataTransfer object to carry information about the dragged data. Without it, the drop event may not be recognized.
    • Custom events: Some frameworks, like React or Angular, add extra layers of event handling. In such cases, using JavaScript ensures that even custom listeners receive the correct event data.
    • Cross-browser testing: JavaScript execution provides more consistent results across browsers, but differences in event handling (especially with security restrictions) may still need to be validated.
    • Performance impact: Executing JavaScript is slightly slower than native actions, so it’s best used only when necessary.

    Using JavaScript for HTML5 drag and drop gives testers fine control over event flow and ensures that the logic behind dynamic UIs is tested, not just the visual motion of elements.

    Common Issues in Selenium Drag and Drop

    Automating drag and drop often fails when Selenium cannot correctly simulate the underlying browser behavior. The problem may appear as the element not moving, the target not responding, or tests passing visually but failing functionally. These failures usually occur due to differences in how browsers, frameworks, and event models handle drag-and-drop actions.

    Here are some of the most frequent issues and what causes them:

    • HTML5 Event Handling: Selenium’s Actions class does not natively fire dragstart, dragover, or drop events required by HTML5. As a result, the visual drag may occur, but the drop logic on the page is never triggered.
    • Hidden or Obstructed Elements: If either the source or target element is covered by another element or not in the viewport, Selenium cannot interact with it. Scrolling into view using JavaScript or waiting for visibility is often necessary.
    • Incorrect Element Locators: Locators that reference container elements instead of the draggable node can cause partial movements or no movement at all. Always identify the exact element that holds the draggable attribute or event listener.
    • Dynamic Page Updates: In modern web apps, drag-and-drop elements are often loaded dynamically using JavaScript. Selenium might attempt to interact before the elements are ready. Explicit waits or re-fetching elements after load are needed to handle this.
    • Offset Miscalculations: Using moveByOffset requires precise coordinates. A small misalignment can result in the element being dropped outside the valid target zone.
    • Browser Compatibility: Drag-and-drop behavior can differ between browsers. For example, some Chrome versions handle Actions-based drag differently from Firefox. Always validate across multiple browsers in parallel.
    • Event Blocking in Frameworks: Libraries like React, Angular, or Vue may prevent default drag-and-drop behavior. Standard Selenium actions might not trigger synthetic events these frameworks rely on. JavaScript-based drag and drop often solves this issue.

    Best Practices for Drag and Drop Automation in Selenium

    Reliable drag-and-drop automation requires careful handling of timing, element visibility, and browser compatibility. A stable test should not just move elements visually but also confirm that the intended application logic executes as expected. 

    Below are best practices that improve consistency and maintainability in drag-and-drop tests:

    • Validate Element Readiness: Always ensure both the source and target elements are visible, enabled, and fully loaded before interaction. Use explicit waits such as WebDriverWait with conditions like ExpectedConditions.visibilityOfElementLocated.
    • Prefer JavaScript for HTML5 Elements: When testing HTML5 or framework-driven pages, use JavaScript-based drag and drop to trigger real browser events. It avoids failures caused by incomplete event simulation through the Actions class.
    • Recalculate Coordinates Dynamically: For pages with responsive layouts, avoid hard-coded pixel offsets. Retrieve element positions at runtime using getLocation() and getSize() to compute reliable offsets.
    • Add Assertions Beyond Visual Movement: After dropping an element, verify that the resulting state is correct. For example, check that the element appears in the target container or that related data updates in the DOM.
    • Use Cross-Browser Testing Early: Browser behavior may vary, especially with custom drag-and-drop libraries. Run your test scripts across multiple browsers and devices early in development to catch inconsistencies.
    • Scroll Elements into View: Before dragging, ensure that both source and target are within the visible viewport. Scrolling them into view with JavaScript prevents failures when elements are partially off-screen.
    • Handle Dynamic Frameworks Carefully: If the application uses libraries like React or Angular, inspect how drag-and-drop events are handled. You may need to trigger synthetic events or wait for re-rendering after dropping.
    • Avoid Unnecessary Delays: Instead of arbitrary Thread.sleep() calls, rely on condition-based waits. This keeps tests faster and more reliable across varying network or rendering speeds.
    • Reuse Utility Functions: Create reusable helper methods for drag-and-drop operations. Centralizing this logic simplifies maintenance and allows easy updates when handling browser or framework-specific quirks.

    Conclusion

    Automating drag and drop in Selenium involves more than moving elements visually. It requires understanding browser event handling, element readiness, and framework behavior to ensure that both the action and the resulting application logic work as intended.

    Running such tests across real browsers and devices is essential to validate consistent drag-and-drop behavior. With BrowserStack Automate, teams can execute Selenium tests on real environments, identify browser-specific issues early, and ensure interactive elements function reliably for every user scenario.

    Run Selenium Tests on Cloud

    Data-rich bug reports loved by everyone

    Get visual proof, steps to reproduce and technical logs with one click

    Make bug reporting 50% faster and 100% less painful

    Rating LogosStars
    4.6
    |
    Category leader

    Liked the article? Spread the word

    Put your knowledge to practice

    Try Bird on your next bug - you’ll love it

    “Game changer”

    Julie, Head of QA

    star-ratingstar-ratingstar-ratingstar-ratingstar-rating

    Overall rating: 4.7/5

    Try Bird later, from your desktop