The click and hold a WebElement action

In the previous section, we have seen the clickAndHold() method, which will click and hold a WebElement at the current position of the cursor. It doesn't care about which element it is dealing with. So, if we want to deal with a particular WebElement on the web page, we have to first move the cursor to the appropriate position and then perform the clickAndHold() action. To avoid the hassle of moving the cursor geometrically, WebDriver provides the developers with another variant or overloaded method of the clickAndHold() method that takes the WebElement as input.

The API syntax is this: 

public Actions clickAndHold(WebElement onElement)

The input parameter for this method is the WebElement that has to be clicked and held. The return type, as in all the other methods of the Actions class, is the Actions instance. Now let's refactor the example in the previous section to use this method, as follows:

@Test
public void shouldClickAndHoldElement() {

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

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

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

The only change is that we have removed the action of moving the cursor to the (200, 20) position and provided the WebElement to the clickAndHold() method that will take care of identifying the WebElement.