Drag and Drop

 Drag and Drop

Drag and Drop is one of the common scenarios in automation. In this tutorial, we are going to study the handling of drag and drop events in Selenium WebDriver using the Actions class

1. Actions in Selenium WebDriver

Actions class in Selenium WebDriver. Using the Actions class, we first build a sequence of composite events and then perform it using Action (an interface which represents a single user-interaction). The different methods of Actions class we will be using here are-

  • clickAndHold(WebElement element) – Clicks a web element at the middle(without releasing).
  • moveToElement(WebElement element) – Moves the mouse pointer to the middle of the web element without clicking.
  • release(WebElement element) – Releases the left click (which is in the pressed state).
  • build() – Generates a composite action.

2. Code Snippet

//WebElement on which drag and drop operation needs to be performed
WebElement fromElement = driver.findElement(By Locator of fromElement);

//WebElement to which the above object is dropped
WebElement toElement = driver.findElement(By Locator of toElement);

//Creating object of Actions class to build composite actions
Actions builder = new Actions(driver);

//Building a drag and drop action
Action dragAndDrop = builder.clickAndHold(fromElement)
.moveToElement(toElement)
.release(toElement)
.build();

//Performing the drag and drop action
dragAndDrop.perform();