Sunday, December 22, 2013

Drag and Drop in Selenium WebDriver

Now we can perform Drag and Drop actions in WebDriver using Actions class. Below is the code for this:
Actions builder = new Actions(driver);
builder.dragAndDrop(source, target);
Here 'source' is the source(from element) web element and 'target' is the target(to element) web element. 
Or
/**
 * Drags the web element fromWebElement and drop at web element
 * toWebElement
 * 
 * @param fromWebElement
 * @param toWebElement
 */
public void dragAndDrop(WebElement fromWebElement, WebElement toWebElement) {
 Actions builder = new Actions(driver);

 Action dragAndDrop = builder.clickAndHold(fromWebElement)
   .moveToElement(toWebElement).release(toWebElement).build();

 dragAndDrop.perform();
}
Please visit here for more details.

Using robot:
/**
 * Drags the web element fromWebElement and drop at web element
 * toWebElement
 * 
 * @param fromWebElement
 * @param toWebElement
 */
public void dragAndDrop(WebElement fromWebElement, WebElement toWebElement) {
 Point coordinates1 = fromWebElement.getLocation();
 Point coordinates2 = toWebElement.getLocation();

 Robot robot = new Robot();

 robot.mouseMove(coordinates1.getX(), coordinates1.getY());
 robot.mousePress(InputEvent.BUTTON1_MASK);
 robot.mouseMove(coordinates2.getX(), coordinates2.getY());
 robot.mouseRelease(InputEvent.BUTTON1_MASK);

}
For more details on mouse actions in Robot please visit here
For more tricks on drag and drop actions please visit my post Drag and Drop tricks in Selenium

No comments:

Post a Comment