The moveToElement action

The moveToElement() method is another method of WebDriver that helps us to move the mouse cursor to a WebElement on the web page.

The API syntax for the moveToElement() method is as follows:

public Actions moveToElement(WebElement toElement)

The input parameter for the preceding method is the target WebElement, where the mouse should be moved. Now go back to the clickAndHold at current location action section of this chapter and try to modify the code to use this method. The following is the code we have written in The click-and-hold-at-current-location action section:

@Test
public void shouldClickAndHold() {

driver.get("http://guidebook.seleniumacademy.com/Sortable.html");

Actions actions = new Actions(driver);

//Move tile3 to the position of tile2
actions.moveByOffset(200, 20)
.clickAndHold()
.moveByOffset(120, 0)
.perform();
}

In the preceding code, we will replace the moveByOffset(x, y) method with the moveToElement(WebElement) method:

@Test
public void shouldClickAndHoldAndMove() {

driver.get("http://guidebook.seleniumacademy.com/Sortable.html");

WebElement three = driver.findElement(By.name("three"));
Actions actions = new Actions(driver);

//Move tile3 to the position of tile2
actions.moveToElement(three)
.clickAndHold()
.moveByOffset(120, 0)
.perform();
}

In the preceding code, we have moved to tile 3, clicked and held it, and then moved to the location of tile 2, by specifying its offset. If you want, you can add the release() method before the perform() method.

There might be a number of ways to achieve the same task. It is up to the user to choose the appropriate ones that best suit the given circumstances.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.144.197