Skip to main content
SeleniumDecoded

Drag and Drop That Works on HTML5 draggable Elements

When Actions.dragAndDrop moves the mouse but nothing drops, dispatch the HTML5 drag events with a shared DataTransfer object from JavaScript instead.

Fragile Verified against Selenium 4.52.0

Problem

A Kanban board uses native HTML5 drag and drop (draggable="true" with dragstart, dragover and drop listeners). new Actions(driver).dragAndDrop(card, column).perform() runs without error, the mouse visibly moves, and the card stays where it was. Synthetic WebDriver mouse input does not reliably start a native drag session in every browser and driver combination.

Solution

Try the Actions API first, with small intermediate moves (which fixes many libraries that need a few mousemove events). If the card did not move, fall back to dispatching the HTML5 drag event sequence in the page with a single shared DataTransfer.

Actions first, HTML5 event fallback
Selenium 4 Fragile
private static final String HTML5_DND = """
const [src, dst] = arguments;
const dt = new DataTransfer();
const fire = (el, type) => el.dispatchEvent(
new DragEvent(type, { bubbles: true, cancelable: true, dataTransfer: dt }));
fire(src, 'dragstart');
fire(dst, 'dragenter');
fire(dst, 'dragover');
fire(dst, 'drop');
fire(src, 'dragend');
""";
public static void dragTo(WebDriver driver, WebElement src, WebElement dst, Supplier<Boolean> moved) {
new Actions(driver)
.clickAndHold(src)
.moveByOffset(5, 5) // nudge: many libraries wait for movement
.moveToElement(dst)
.pause(Duration.ofMillis(150))
.release()
.perform();
if (!moved.get()) {
((JavascriptExecutor) driver).executeScript(HTML5_DND, src, dst);
}
new WebDriverWait(driver, Duration.ofSeconds(5)).until(d -> moved.get());
}
WebElement card = driver.findElement(By.cssSelector("[data-card-id='42']"));
WebElement done = driver.findElement(By.cssSelector("[data-column='done']"));
dragTo(driver, card, done,
() -> !driver.findElements(By.cssSelector("[data-column='done'] [data-card-id='42']")).isEmpty());
HTML5_DND = """
const [src, dst] = arguments;
const dt = new DataTransfer();
const fire = (el, type) => el.dispatchEvent(
new DragEvent(type, { bubbles: true, cancelable: true, dataTransfer: dt }));
fire(src, 'dragstart');
fire(dst, 'dragenter');
fire(dst, 'dragover');
fire(dst, 'drop');
fire(src, 'dragend');
"""
def drag_to(driver, src, dst, moved):
(ActionChains(driver)
.click_and_hold(src)
.move_by_offset(5, 5)
.move_to_element(dst)
.pause(0.15)
.release()
.perform())
if not moved():
driver.execute_script(HTML5_DND, src, dst)
WebDriverWait(driver, 5).until(lambda d: moved())
card = driver.find_element(By.CSS_SELECTOR, "[data-card-id='42']")
done = driver.find_element(By.CSS_SELECTOR, "[data-column='done']")
drag_to(driver, card, done,
lambda: bool(driver.find_elements(By.CSS_SELECTOR, "[data-column='done'] [data-card-id='42']")))
const HTML5_DND = `
const [src, dst] = arguments;
const dt = new DataTransfer();
const fire = (el, type) => el.dispatchEvent(
new DragEvent(type, { bubbles: true, cancelable: true, dataTransfer: dt }));
fire(src, 'dragstart');
fire(dst, 'dragenter');
fire(dst, 'dragover');
fire(dst, 'drop');
fire(src, 'dragend');`;
async function dragTo(driver, src, dst, moved) {
await driver.actions()
.move({ origin: src })
.press()
.move({ x: 5, y: 5, origin: 'pointer' })
.move({ origin: dst })
.pause(150)
.release()
.perform();
if (!(await moved())) await driver.executeScript(HTML5_DND, src, dst);
await driver.wait(moved, 5000, 'drop did not take effect');
}
const string Html5Dnd = """
const [src, dst] = arguments;
const dt = new DataTransfer();
const fire = (el, type) => el.dispatchEvent(
new DragEvent(type, { bubbles: true, cancelable: true, dataTransfer: dt }));
fire(src, 'dragstart');
fire(dst, 'dragenter');
fire(dst, 'dragover');
fire(dst, 'drop');
fire(src, 'dragend');
""";
public static void DragTo(IWebDriver driver, IWebElement src, IWebElement dst, Func<bool> moved)
{
new Actions(driver)
.ClickAndHold(src)
.MoveByOffset(5, 5)
.MoveToElement(dst)
.Pause(TimeSpan.FromMilliseconds(150))
.Release()
.Perform();
if (!moved()) ((IJavaScriptExecutor)driver).ExecuteScript(Html5Dnd, src, dst);
new WebDriverWait(driver, TimeSpan.FromSeconds(5)).Until(_ => moved());
}

Why It Works

HTML5 drag and drop is driven by DragEvents, not mouse events. The app’s handlers usually call e.dataTransfer.setData() in dragstart and read it back with getData() in drop. Dispatching the sequence with one shared DataTransfer object lets that data round-trip exactly as in a real drag, and dragover with cancelable: true gives the drop target the chance to call preventDefault(), which is what marks it as a valid drop zone.

Which Approach for Which Library

ImplementationWorks with ActionsNeeds JS events
Native HTML5 (draggable="true")Sometimes; depends on browser and driverUsually
SortableJS (default)Often failsYes
SortableJS with forceFallback: trueYes (mouse/pointer based)No
react-beautiful-dnd / dnd-kit / pointer-based librariesYes, with small intermediate movesNo, JS DragEvents are ignored
jQuery UI draggableYesNo

Gotchas

  • Always verify the outcome. The moved check is essential: neither approach throws when the drop is ignored. Assert on the DOM (or the API) after dragging.
  • JS events skip real user behaviour. No hover styling, no auto-scroll near edges, no pointer capture. This is a test of the drop logic, not the drag experience.
  • Pointer-based libraries ignore DragEvents. If the fallback does nothing either, the library listens to pointerdown/pointermove; use Actions with several small moveByOffset steps instead.
  • File drops from the desktop are a different problem; use a file input or see the file upload lesson.
  • Mark the robustness honestly. These tests break when the board library is upgraded. Keep the number of drag tests small and push sorting logic tests down to the API or unit level.

Learn the theory