We use cookies to analyze site traffic and show personalized ads. You can accept all cookies or decline personalized advertising.
Learn more in our Privacy Policy.
Move the mouse cursor and trigger hover effects using moveToElement
In this practice lab, you will learn how to simulate mouse movement and hover interactions with Selenium using the Actions class.
Hover actions are essential for testing UI elements that appear or change based on mouse position:
Moves the mouse to the in-view center of the element without performing any click.
:hover pseudo-classmouseenter and mouseover eventsAfter hovering, verify that the expected behavior occurred:
Dropdown Menus
Navigation menus that expand when hovering over menu items
Tooltips
Information popups that appear when hovering over icons or text
Image Galleries
Overlay controls or zoom effects triggered by mouse hover
Imagine a page called "Hover Playground" with the following interactive elements:
Interact with these elements directly to see how Selenium's hover actions would work!
If you were doing this with a real mouse:
Your Selenium code will automate these exact behaviors using moveToElement().
123456789101112131415161718192021222324WebElement hoverCard = driver.findElement(By.id("hover-card"));
WebElement tooltipTrigger = driver.findElement(By.id("tooltip-trigger"));
WebElement menuTrigger = driver.findElement(By.id("menu-trigger"));
Actions actions = new Actions(driver);
// 1. Hover over the hover card
actions.moveToElement(hoverCard).perform();
// 2. Hover over the tooltip trigger
actions.moveToElement(tooltipTrigger).perform();
// Wait for tooltip to appear and verify
WebElement tooltip = driver.findElement(By.cssSelector(".tooltip"));
assert tooltip.isDisplayed();
// 3. Hover over the menu to expand dropdown
actions.moveToElement(menuTrigger).perform();
// Wait for menu and click a menu item
WebElement menuItem = driver.findElement(By.linkText("Product 1"));
actions.click(menuItem).perform();
driver.quit();Ensure the target element is in the viewport before using moveToElement(). If the element is off-screen, Selenium may fail to hover correctly. Scroll the element into view first if needed.
After hovering, use explicit waits to ensure hover-triggered elements (tooltips, menus) have time to appear before making assertions or clicks. CSS animations may take time to complete.
For dropdown menus, use the pattern: moveToElement(menu).perform()then click(menuItem).perform(). This ensures the menu expands before clicking items.