In this tutorial, we will learn handling Keyboard and Mouse Event in Selenium Webdriver
Handling special keyboard and mouse events are done using the Advanced User Interactions API. It contains the Actions and the Action classes that are needed when executing these events. The following are the most commonly used keyboard and mouse events provided by the Actions class.
In the following example, we shall use the moveToElement() method to mouse-over on one Mercury Tours' table rows. See the example below.
The cell shown above is a portion of a <TR> element. If not hovered, its color is #FFC455 (orange). After hovering, the cell's color becomes transparent. It becomes the same color as the blue background of the whole orange table.
Step 1: Import the Actions and Action classes.
Step 2: Instantiate a new Actions object.
Step 3: Instantiate an Action using the Actions object in step 2.
In this case, we are going to use the moveToElement() method because we are simply going to mouse-over the "Home" link. The build() method is always the final method used so that all the listed actions will be compiled into a single step.
Step 4: Use the perform() method when executing the Action object we designed in Step 3.
Below is the whole WebDriver code to check the background color of the <TR> element before and after the mouse-over.
package newproject; import org.openqa.selenium.*; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.interactions.Action; import org.openqa.selenium.interactions.Actions; public class PG7 { public static void main(String[] args) { String baseUrl = "http://newtours.demoaut.com/"; System.setProperty("webdriver.firefox.marionette","C:\\geckodriver.exe"); WebDriver driver = new FirefoxDriver(); driver.get(baseUrl); WebElement link_Home = driver.findElement(By.linkText("Home")); WebElement td_Home = driver .findElement(By .xpath("//html/body/div" + "/table/tbody/tr/td" + "/table/tbody/tr/td" + "/table/tbody/tr/td" + "/table/tbody/tr")); Actions builder = new Actions(driver); Action mouseOverHome = builder .moveToElement(link_Home) .build(); String bgColor = td_Home.getCssValue("background-color"); System.out.println("Before hover: " + bgColor); mouseOverHome.perform(); bgColor = td_Home.getCssValue("background-color"); System.out.println("After hover: " + bgColor); driver.close(); } }
The output below clearly states that the background color became transparent after the mouse-over.
You can build a series of actions using the Action and Actions classes. Just remember to close the series with the build() method. Consider the sample code below.
Summary
Handling special keyboard and mouse events are done using the AdvancedUserInteractions API.
Frequently used Keyword and Mouse Events are doubleClick(), keyUp, dragAndDropBy, contextClick & sendKeys.