How to perform Mouse Hover Action in Selenium
Hovering is a fundamental digital action that involves placing the mouse cursor on the target link or button. Users mainly use the mouse hover action to access sub-menu items
This is a fundamental and frequently used action for more websites, and thus it must be created and tested to work perfectly for browsers and customers at all times.
Thankfully, the hover mouse hover action can be automated in Selenium using the Actions class. This article will illustrate how one can automate the hover operation in Selenium with relevant code snippets.
How to perform mover hover in Selenium?
Prerequisite: One needs to be familiar with the different locator strategies in Selenium to locate specific web elements before being able to automate the mouse hover.
The first step for hovering over an element is to locate that particular parent element. Then, the tester can perform the hover operation using the Actions class.
Refer to the code snippet below:
WebElement ele = driver.findElement(By.xpath("<xpath>"));//Creating object of an Actions class
Actions action = new Actions(driver);//Performing the mouse hover action on the target element.
action.moveToElement(ele).perform();
Now let’s explore the process to perform d for elements in the sub-menu.
The first step here would be to locate the main menu (AKA parent menu). Once that is done, the second step is to locate the desired element (child element) from the available options in the sub-menu. The final step would be to click on that child element.
Refer to the code snippet below:
// Locating the Main Menu (Parent element)
WebElement mainMenu = driver.findElement(By.xpath("<Xpath of the Main menu"));//Instantiating Actions class
Actions actions = new Actions(driver);//Hovering on main menu
actions.moveToElement(mainMenu);// Locating the element from Sub Menu
WebElement subMenu = driver.findElement(By.xpath("<Xpath of the sub element>"));//To mouseover on sub menu
actions.moveToElement(subMenu);//build()- used to compile all the actions into a single step
actions.click().build().perform();
The code above first locates the parent element and hovers over it and as soon as the sub-menu renders, it locates the child element from the sub-menu, hover, and finally performs the click operation on it.