There might be some cases when you want to perform Mouse Hover in Selenium WebDriver, which means moving your mouse over an element before doing some operation. It could be for checking tooltips or enabling some context menu or any other type of reason.
In Selenium automation, we can utilize the Actions class to get this kind of operation. Actions class provides methods for an operation like Mouse Hover, Left click, Right click, etc. Mostly it provides a method to replicate any operation which can be performed by a real keyboard/mouse.
For understanding how to use it, let’s consider that we have a Menu that displays submenus when we move the mouse over it (like a mega menu).
In order to click an item in the submenu, first we need to hover the mouse pointer on the menu element right?
In the below example, notice how the method MoveToElement is used to replicate the mouse hover on MenuElement and then on the submenu item with XPath “Xpath-Of-Menu-Item-Element”)
Example code for Mouse Hover in Selenium WebDriver
Actions Actions = New Actions(Driver); WebElement MenuElement = Driver.FindElement(By.Id("Menu-Element-Id")); Actions.MoveToElement(MenuElement).MoveToElement(Driver.FindElement(By.Xpath("Xpath-Of-Menu-Item-Element"))).Click();