Selenium Mouse And Keyboard Actions
The Actions Class
Regular click() and sendKeys() commands handle simple interactions. Some pages need advanced gestures like hovering, dragging, or holding a key. Selenium provides the Actions class for these complex movements.
Diagram: Actions Class Building A Sequence
Actions Builder
|
|-- moveToElement()
|-- clickAndHold()
|-- dragAndDrop()
|-- keyDown() / keyUp()
|
v
.build().perform()
|
v
Executes the full sequence
Creating An Actions Object
Actions actions = new Actions(driver);
Mouse Hover
Many navigation menus reveal a submenu only when a user hovers the mouse over a parent item.
WebElement menu = driver.findElement(By.id("courses-menu"));
actions.moveToElement(menu).perform();
This moves the virtual mouse over the menu item, triggering any hover-based dropdown to appear.
Right Click
WebElement image = driver.findElement(By.id("course-thumbnail"));
actions.contextClick(image).perform();
This performs a right-click, opening a context menu on elements that support one.
Double Click
WebElement editableText = driver.findElement(By.id("bio-field"));
actions.doubleClick(editableText).perform();
This performs a double-click, often used to select a word or activate an inline editor.
Click And Hold
actions.clickAndHold(image).perform();
This presses the mouse button down without releasing it, useful before a drag movement.
Drag And Drop
WebElement source = driver.findElement(By.id("draggable-item"));
WebElement target = driver.findElement(By.id("drop-zone"));
actions.dragAndDrop(source, target).perform();
This picks up the source element and drops it onto the target element in one motion, common on file upload zones and kanban boards.
Keyboard Key Combinations
WebElement textBox = driver.findElement(By.id("search"));
actions.click(textBox)
.keyDown(Keys.CONTROL)
.sendKeys("a")
.keyUp(Keys.CONTROL)
.perform();
This clicks the text box, holds the Control key, presses A to select all text, then releases Control, mimicking a keyboard shortcut.
Chaining Multiple Actions
actions.moveToElement(menu)
.pause(Duration.ofMillis(500))
.click(driver.findElement(By.linkText("Selenium Course")))
.build()
.perform();
This hovers over a menu, pauses briefly for the submenu animation to finish, then clicks a link inside that submenu.
Practical Example
An online quiz page lets students drag answer options into matching boxes. A test script locates each draggable answer and its matching drop zone, then performs dragAndDrop() for every pair to confirm the quiz interface accepts the interaction correctly.
