Saturday, September 14, 2019

Post#64.Drag and Drop (moveToElement) in Selenium


dragAndDrop and clickAndHold
Drag and dropping an element in webpages is rare scenario, but it does exist. dragAndDrop Method in Actions class helps the selenium user to perform this task. 
Consider you want to drag and drop the 1st element to 2nd Element as shown in below image.

Website Link: http://www.testingbar.com/drag-and-drop/
Performs click and hold at the location of the source element by clickAndHold() method, moves to the location of the target element by moveToElement() method, then releases the mouse by release Method.

After Drag and Drop Operation it will be shown as below image.

User Action: Click and hold the 1st element QMove to target Element Q Release the Mouse
Script:
package pack3;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;

public class DragAndDrop {

public static void main(String[] args) {

WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://www.testingbar.com/drag-and-drop/");
//Locate which element you want to drag
WebElement dragelementfrom = driver.findElement(By.xpath("//*[@id='draggable']"));
//Locate element where you wants to drop.
WebElement dragelementto = driver.findElement(By.xpath("//*[@id='droppable']"));
Actions builder = new Actions(driver);
Action dragAndDrop = builder.clickAndHold(dragelementfrom).moveToElement(dragelementto).release(dragelementto).build();
dragAndDrop.perform();
}
}
Here release() method Releases the pressed left mouse button at the current mouse location pointer.


No comments:

Post a Comment