Q11 of 37 · Selenium
What is the Actions class in Selenium and when do you use it?
Short answer
Short answer: The Actions class builds composite mouse and keyboard sequences — hover, drag-and-drop, right-click, key chords, double-click. You chain calls and finish with `.perform()`. Use it whenever a single click/sendKeys isn't enough.
Detail
WebElement.click() and sendKeys() cover most interactions, but UIs increasingly rely on richer input: hovering to reveal a menu, dragging a kanban card, holding shift while clicking, right-click context menus. That's where the Actions builder comes in.
You construct an Actions instance, chain operations, and call .perform() to execute the sequence atomically:
Actions a = new Actions(driver);
a.moveToElement(menu).pause(Duration.ofMillis(150))
.click(menuItem)
.perform();
Common scenarios:
- Hover →
moveToElementreveals dropdowns and tooltips that only appear on:hover. - Drag-and-drop →
dragAndDrop(source, target)or the long formclickAndHold → moveToElement → release. The long form is more reliable on HTML5 dnd than the shortcut. - Right-click →
contextClick(element). - Double-click →
doubleClick(element). - Key chords →
keyDown(Keys.SHIFT).click(item).keyUp(Keys.SHIFT)for shift-click, orkeyDown(Keys.CONTROL).sendKeys("a").keyUp(Keys.CONTROL)for Ctrl+A.
The trap to watch: everything before .perform() is queued, not executed. Forgetting .perform() is the most common Actions bug — code runs, no error, no behaviour, test fails confusingly.
For HTML5 native drag-and-drop, browsers often refuse to fire the right dragstart/drop events from synthetic Selenium events; you may need to dispatch the events via executeScript instead. Worth knowing — and worth trying Actions first because when it works, it's cleaner.
// EXAMPLE
Actions actions = new Actions(driver);
// Hover to reveal a submenu, then click an item inside it
actions.moveToElement(driver.findElement(By.cssSelector("[data-test=user-menu]")))
.pause(Duration.ofMillis(200))
.click(driver.findElement(By.cssSelector("[data-test=logout]")))
.perform();
// Shift+click — multi-select in a list
actions.keyDown(Keys.SHIFT)
.click(secondRow)
.keyUp(Keys.SHIFT)
.perform();