Multilevel menu handling using Actions class in Selenium
Use cases of Actions class:
During our automation script execution, we may encounter cases where, we need to move an element or move to an element, hover over, click and hold, scroll, drag and drop, double click etc. All these can be easily handled by Actions class.
Declaration :
To be able to use the Actions class, we need create an Actions object first.
WebDriver driver = new ChromeDriver();
Actions action = new Actions(driver);
Multilevel menu handling using Actions :
Let's take an example of a grocery shopping website - Big Basket, where we have a multilevel menu as below :
If we click on a certain option, it will redirect the page to that option and we can't have that. We want to navigate directly to out desired submenu.
WebDriver driver = new ChromeDriver();
driver.get("https://www.bigbasket.com/");
driver.manage().window().maximize();
//find main menu By locator
WebElement shopMenu = driver.findElement(By.xpath("(//button[contains(@class,'content-center')])[2]"));
//create Actions class object
Actions action = new Actions(driver);
//click on the main menu
action.click(shopMenu).build().perform();
Thread.sleep(2000);
//find the sub menu item elements :
WebElement kitchenMenu = driver.findElement(By.linkText("Kitchen, Garden & Pets"));
action.moveToElement(kitchenMenu).build().perform();
Thread.sleep(2000);
WebElement steelUtensils = driver.findElement(By.linkText("Steel Utensils"));
action.moveToElement(steelUtensils).build().perform();
Thread.sleep(2000);
WebElement bowls = driver.findElement(By.linkText("Bowls & Vessels"));
action.click(bowls).build().perform();
SendKeys and Click :
Using Actions class object we can perform the sendKeys(String value) and click() operations as well. We can avoid the ElementClickInterceptedException using the Actions class click(WebElement targetElement) method.
There are several useful fun methods available in Actions class which can be used as required.