How to hover an element in selenium

When testing web applications, itโ€™s common to encounter hidden elements such as dropdown menus or tooltips that only appear on hover. Using Selenium Actions class, we can easily hover a menu item to reveal its sub-menu items. We can also use JavaScriptExecutor in cases where Selenium cannot directly interact with hidden elements.

๐Ÿ“Œ Why Hover is Important in Selenium?

  • Many navigation menus use hover to display sub-menu items.
  • Hover actions help you test dynamic menus and tooltips.
  • Hidden elements can be revealed using Actions.moveToElement() with onmouseover.

๐Ÿ“Œ Example 1 โ€“ Hover Using Selenium Actions Class

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

public class HoverExample {
public static void main(String[] args) {
// Initialize WebDriver (Chrome)
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();

    // Open URL
    driver.get("https://www.example.com"); // Replace with your target URL

    // Locate the element to hover
    WebElement elementToHover = driver.findElement(By.id("menu")); // Replace with your locator

    // Create Actions object
    Actions actions = new Actions(driver);

    // Perform hover action
    actions.moveToElement(elementToHover).perform();

    // Optional: wait a bit to observe hover effect
    try {
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    // Close browser
    driver.quit();
}

}

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Testingtalkslatest.com - A project by CreativeHub IT Solutions.
Contact Us At: support@testingtalkslatest.com
Our Partner websites - Classified Hub , CodesToolbox , CodesToolbox
Scroll to Top
0
Would love your thoughts, please comment.x
()
x