Selenium + Java · Lesson 23 of 44

0/44 done

Module 23: Mouse & Keyboard Actions

23. Advanced Mouse Actions, Drag & Drop, and Key Combinations

16 minlesson

Your task

Implement hoverAndClick:

  1. Accept WebDriver driver, WebElement hoverElement, and WebElement clickElement.
  2. Use Actions to moveToElement(hoverElement), then click(clickElement), then perform().

Write it in the editor, then press Check answer (Ctrl + Enter).

The Selenium Actions Class

Always end action chains with .build().perform() or .perform():

java
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.Keys;

Actions actions = new Actions(driver);

// Hover to reveal submenu:
WebElement navMenu = driver.findElement(By.id("nav-products"));
actions.moveToElement(navMenu).perform();

// Context click (Right-click):
actions.contextClick(navMenu).perform();

// Drag and drop:
WebElement source = driver.findElement(By.id("draggable"));
WebElement target = driver.findElement(By.id("droppable"));
actions.dragAndDrop(source, target).perform();

// Modifier keys (Ctrl+A):
actions.keyDown(Keys.CONTROL).sendKeys("a").keyUp(Keys.CONTROL).perform();

Key Takeaways & Walkthrough Summary

Complex interactions like hovering over navigation menus, right-clicking for context menus, and drag-and-drop require the Selenium Actions class. In this lesson, you will master chaining actions and calling build().perform(). Let's master the Actions class!

Part of the Selenium + Java course (Selenium with Java). Practice this concept live in the Selenium Online Compiler or explore our free automation practice form.

Common Doubts & Lesson Q&A

Why did my Actions chain do nothing on the browser?

You forgot to call .perform() at the end of the action chain! Without .perform(), the actions are only queued, not executed.

Ready? Solve the task in the editor

Use Check answer to mark it complete. Hints are there if you need them.

Java
Skip