Mouse hover is performed using Actions.moveToElement() to simulate moving the cursor over an element.
Basic mouse hover:
Java
Actions actions = new Actions(driver);
WebElement menu = driver.findElement(By.id("navMenu"));
actions.moveToElement(menu).perform();
Hover and click a sub-menu item:
Java
WebElement mainMenu = driver.findElement(By.id("productsMenu"));
WebElement subMenu = driver.findElement(By.id("electronicsSubmenu"));
Actions actions = new Actions(driver);
actions.moveToElement(mainMenu)
.moveToElement(subMenu)
.click()
.build()
.perform();
Hover to reveal tooltip text:
Java
WebElement icon = driver.findElement(By.id("helpIcon"));
actions.moveToElement(icon).perform();
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));
WebElement tooltip = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.className("tooltip"))
);
System.out.println("Tooltip: " + tooltip.getText());
Common use cases:
- ✓Navigation mega menus
- ✓Hover-to-reveal buttons
- ✓Tooltips and popovers
- ✓Drag handles that appear on hover
