We use cookies to analyze site traffic and show personalized ads. You can accept all cookies or decline personalized advertising.
Learn more in our Privacy Policy.
Learn dragAndDrop and clickAndHold for moving elements on the page
In this practice lab, you will learn how to simulate drag-and-drop interactions with Selenium using the Actions class.
Drag-and-drop is a common UI pattern used in many applications:
The high-level method that combines all drag-and-drop steps into one action.
What it does: Clicks and holds the source element, moves to the center of the target element, then releases.
Drags an element by a specific pixel offset instead of to a target element.
What it does: Clicks and holds the source, moves by the specified x and y offsets, then releases.
For complex scenarios, you can manually control each step of the drag-and-drop operation:
clickAndHold(source) - Press and hold the mouse button on the sourcemoveToElement(target) - Move the mouse (while holding) to the targetrelease() - Release the mouse button at the current positionImagine a page called "Drag and Drop Playground" with the following interactive elements:
Drag the box to the drop zone
Drag the slider handle to adjust value
Interact with these elements directly to see how Selenium's drag actions would work!
If you were doing this with a real mouse:
Your Selenium code will automate these exact behaviors using dragAndDrop() and dragAndDropBy().
1234567891011121314151617181920WebElement draggable = driver.findElement(By.id("draggable"));
WebElement droppable = driver.findElement(By.id("droppable"));
WebElement slider = driver.findElement(By.id("slider"));
Actions actions = new Actions(driver);
// 1. Simple drag and drop from source to target
actions.dragAndDrop(draggable, droppable).perform();
// 2. Drag slider by pixel offset (100 pixels right)
actions.dragAndDropBy(slider, 100, 0).perform();
// 3. Manual drag-and-drop with intermediate steps
actions.clickAndHold(draggable)
.moveToElement(droppable)
.pause(Duration.ofMillis(500))
.release()
.perform();
driver.quit();Always try dragAndDrop(source, target) first. It's the simplest approach and works for most scenarios. Only use manual clickAndHold/moveToElement/release if dragAndDrop() fails.
Both source and target elements must be visible and within the viewport. Scroll them into view if necessary before attempting drag-and-drop operations.
Drag-and-drop targets should have stable, unique IDs or data attributes. Avoid using complex CSS selectors or XPath expressions that might break if the page structure changes.