The dragAndDropBy action

There might be many instances where we may have to drag and drop components or WebElements of a web page. We can accomplish that by using many of the actions seen until now. But WebDriver has given us a convenient out-of-the-box method to use. Let's see its API syntax.

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

public Actions dragAndDropBy(WebElement source, int xOffset,int yOffset)

The WebElement input parameter is the target WebElement to be dragged, the xOffset parameter is the horizontal offset to be moved, and the yOffset parameter is the vertical offset to be moved.

Let's see a code example for it. Open the HTML file, DragMe.html, provided with this book. It has a square box, as shown in the following screenshot:

You can actually drag that rectangle to any location on the web page. Let's see how we can do that, using WebDriver. The following is the code example for that:

@Test
public void shouldDrag() {

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

WebElement dragMe = driver.findElement(By.id("draggable"));
Actions actions = new Actions(driver);
actions.dragAndDropBy(dragMe, 300, 200).perform();
}

In the preceding code, dragMe is the WebElement that is identified by its id, and that is dragged 300px horizontally and 200px vertically. The following screenshot shows how an element is dragged from this position:

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

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