Q11 of 37 · Selenium

What is the Actions class in Selenium and when do you use it?

SeleniumMidseleniumactionshoverdrag-drop

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:

  • HovermoveToElement reveals dropdowns and tooltips that only appear on :hover.
  • Drag-and-dropdragAndDrop(source, target) or the long form clickAndHold → moveToElement → release. The long form is more reliable on HTML5 dnd than the shortcut.
  • Right-clickcontextClick(element).
  • Double-clickdoubleClick(element).
  • Key chordskeyDown(Keys.SHIFT).click(item).keyUp(Keys.SHIFT) for shift-click, or keyDown(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();

// WHAT INTERVIEWERS LOOK FOR

Knowing Actions exists, listing 2-3 use cases (hover, drag, key chord), and remembering that .perform() is the trigger.

// COMMON PITFALL

Forgetting .perform() and concluding 'Actions doesn't work,' or assuming dragAndDrop will reliably fire HTML5 dnd events on every site (it often won't — fall back to JS dispatch).