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

The Selenium Actions Class

Always end action chains with .build().perform() or .perform():
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();

Task

  • Implement hoverAndClick:
  • 1. Accept WebDriver driver, WebElement hoverElement, and WebElement clickElement.
  • 2. Use Actions to moveToElement(hoverElement), then click(clickElement), then perform().
πŸ’‘Common doubts
Did you like the problem?
Lesson 23 of 44
Java
Loading code editor…
Next