The moveByOffset action
The moveByOffset() method is used to move the mouse from its current position to another point on the web page. Developers can specify the x distance and the y distance the mouse has to be moved. When the page is loaded, generally the initial position of the mouse would be (0, 0), unless there is an explicit focus declared by the page.
The API syntax for the moveByOffset() method is as follows:
public Actions moveByOffset(int xOffSet, int yOffSet)
In the preceding code, xOffSet is the input parameter providing the WebDriver the amount of offset to be moved along the x axis. A positive value is used to move the cursor to the right, and a negative value is used to move the cursor to the left.
yOffSet is the input parameter providing the WebDriver the amount of offset to be moved along the y axis. A positive value is used to move the cursor down along the y axis, and a negative value is used to move the cursor toward the top.
When the xOffSet and yOffSet values result in moving the cursor out of the document, a MoveTargetOutOfBounds exception is raised.
Let's see a working example of it. The objective of the following code is to move the cursor on to tile 3 on the web page:
@Test
public void shouldMoveByOffSet() {
driver.get("http://guidebook.seleniumacademy.com/Selectable.html");
WebElement three = driver.findElement(By.name("three"));
System.out.println("X coordinate: " + three.getLocation().getX()
+ ", Y coordinate: " + three.getLocation().getY());
Actions actions = new Actions(driver);
actions.moveByOffset(three.getLocation().getX() + 1, three.
getLocation().getY() + 1);
actions.perform();
}
The output will be as follows:
We have added +1 to the coordinates, because if you observe the element in Firebug, we have a style border of 1 px. The border is a CSS-style attribute, which when applied to an element will add a border of the specified color around the element, with the specified amount of thickness. Though the previous code does move your mouse over tile 3, we don't realize this, because we are not performing any action there. We will see this shortly, when we use the moveByOffset() method in combination with the click() method.