Mouse Hover Actions Using Actions Class In Selenium
Mouse Hover Actions Using Actions Class:
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.
Must Read: 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.
Mouse hover actions on an element using Actions Class:
WebElement ele = driver.findElement(By.xpath("xpath")); //Create object 'action' of an Actions class Actions action = new Actions(driver); //Mouseover on an element action.moveToElement(ele).perform();
Mouse hover actions on a sub-element using Actions Class:
If we want to click on the sub-element, first we need to mouse hover on the parent-element and then sub-element and click on it.
//Main Menu WebElement mainMenu = driver.findElement(By.linkText("main_menu_link")); //Create object 'action' of an Actions class Actions actions = new Actions(driver); //To mouseover on main menu actions.moveToElement(mainMenu); //Sub Menu WebElement subMenu = driver.findElement(By.linkText("sub_menu_link")); //To mouseover on sub menu actions.moveToElement(subMenu); //build() method is used to compile all the actions into a single step actions.click().build().perform();
Or
//Main Menu WebElement mainMenu = driver.findElement(By.linkText("main_menu_link")); //Create object 'action' of an Actions class Actions action = new Actions(driver); //moving to the main menu and then sub menu and clicking on it using object of the Actions class action.moveToElement(mainMenu).moveToElement(driver.findElement(By.linkText("sub_menu_link"))).click().build().perform();
If you are not regular reader of my blog then I highly recommend you to signup for the free email newsletter using the below link.
How to handle dynamic values in selenium
Hi Manju, check this post on dynamic xpath in selenium
Hi Menus like,
In your website “https://www.softwaretestingmaterial.com/mouse-hover-actions-using-selenium/”
Go to tutorials –> Selenium —> Jenkins
i want to click on jenkins.
then how should i write the code?
Hi Prasanthi,
try this out..