Sunday, December 22, 2013

Mouse hover in Selenium WebDriver

In some web applications we need to mouse hover on one element to make visible of another element. In those cases we need to mouse over on first element before performing any action on second element.

For example, when we mouse hover on certain menus, the sub-menus appears. In such cases we need to use the following ways to hover on web elements:

  1. Using Actions class:
  2. We can use WebDriver's Actions class to perform hover action as below:
    Actions actions = new Actions(driver);
    WebElement mainMenu = driver.findElement(By.cssSelector("#headerMenu"));
    actions.moveToElement(mainMenu);
    
    WebElement subMenu = driver.findElement(By.cssSelector("#headerMenu .subMenu"));
    actions.moveToElement(subMenu);
    actions.click();
    
    actions.perform();
    
    Don't forget to call 'perform()' method. This action won't complete unless you call perform().

  3. Using JQuery:
  4. You can use JQuery selector with mouseover() function as below:
    String aJQueryString = "jQuery(\"#headerMenu\").mouseover()"; 
    WebElement element = findElementByJQuery(aJQueryString);
    
    For understanding "findElementByJQuery(aJQueryString)" method and use please go through my post "Finding web elements by executing JQuery script".


  5. Using Robot:
  6. You can use Robot class to find out location of the web element in the screen and then by hover on it as below:
    /**
     * Mouse overs on the element by its locator by
     * 
     * @param by
     *            a locator e.g. xpath, css, name, id, class name etc
     */
    public void mouseOverOnElementUsingRobot(By by) {
     try {
      Point coordinates = driver.findElement(by).getLocation();
      Robot robot = new Robot();
      robot.mouseMove(coordinates.getX(), coordinates.getY() + 60);
      /*
       * WebDriver provide document coordinates, where as Robot class is
       * based on Screen coordinates, so I have added +60 to compensate
       * the browser header. You can even adjust if needed.
       */
    
     } catch (AWTException e) {
      log.error("Failed to mouseover on the element '" + by + "'. " + e);
     }
    }
    

No comments:

Post a Comment