Mouse Hover Actions Using Actions Class In Selenium


Sometimes, sub menu items render in DOM only when we mouse hover on main menu. In that case, we face difficulty to click on sub menu item. In order to perform mouse hover actions, we need to chain all of the actions that we want to achieve in one go. To do this we need to make the driver move to the parent element that has child elements and click on the child element.


To achieve this we use Actions class in Selenium WebDriver.
Create object of an Actions Class by passing the WebDriver instance. With the object of the Actions class, driver moves to the main menu and then to the sub menu and click on it.



Let’s see some scenarios.
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 MouseHover {


public static void main(String[] args) {


System.setProperty("webdriver.chrome.driver","C://Drivers/chromedriver_win32/chromedriver.exe");
WebDriver driver=new ChromeDriver();

driver.get("http://opensource.demo.orangehrmlive.com/index.php/auth/login");

driver.findElement(By.name("txtUsername")).sendKeys("Admin");
driver.findElement(By.name("txtPassword")).sendKeys("admin");
driver.findElement(By.name("Submit")).click();

WebElement admin=driver.findElement(By.xpath("//*[@id='menu_admin_viewAdminModule']/b"));
WebElement usermgnt=driver.findElement(By.xpath("//*[@id='menu_admin_UserManagement']"));
WebElement users=driver.findElement(By.xpath("//*[@id='menu_admin_viewSystemUsers']"));

Actions act=new Actions(driver); // Actions class object

//MouseHover action
act.moveToElement(admin).moveToElement(usermgnt).moveToElement(users).click().build().perform();

}

}

Followers