Skip to main content

You are here

Hover the mouse on a menu and click on a resulting dropdown menu option

This piece of code allows you find and click on a drop down menu resulting from hovering the mouse over a main menu option. The issue with a menu resulting from hovering the mouse is that the sub menu elements are not available for selection until the drop down menu appears. As long as focus remains on the menu, one can choose from the drop down.

In the program below, I have used the Actions class to initiate mouse movement. The steps taken are:

1. Load the website
2. Identify the main menu option that results in a drop down menu
3. Configure and move the mouse to this identified menu link
4. Wait for 5 seconds (this allows the drop down appear)
5. Locate and click on a link on the resulting drop down
6. Done!

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class HoverAndClickOnAMenu {
public static void main(String[] args) {

//initialise browser
WebDriver driver = new FirefoxDriver();

//locate the menu to hover over using its xpath
WebElement menu = driver.findElement(By.xpath("//*[@id='music']"));

//Initiate mouse action using Actions class
Actions builder = new Actions(driver);   

// move the mouse to the earlier identified menu option

// wait for max of 5 seconds before proceeding. This allows sub menu appears properly before trying to click on it
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@id='subNav_music_menu']/tbody/tr[2]/td[1]/a[1]")));  // until this submenu is found

//identify menu option from the resulting menu display and click
WebElement menuOption = driver.findElement(By.xpath("//*[@id='subNav_music_menu']/tbody/tr[2]/td[1]/a[1]"));;




No votes yet

Add new comment

Type the characters you see in this picture. (verify using audio)
Type the characters you see in the picture above; if you can't read them, submit the form and a new image will be generated. Not case sensitive.


Note that the codes and ideas expressed on this site are the authors personal views. The content of this website are the personal notes based on the learning experience of the author. The author will not be responsible for any error or damages resulting from you using the content of this website.

Premium Drupal Themes by Adaptivethemes