How to drag and drop an element in Selenium WebDriver?

During automating real time applications, we may face certain scenarios where in we need to automate drag an element from one position and drop to another position.

To achieve these automation steps, Selenium has provided an actions class. Using this actions class we can automate drag and drop of an element.

Steps to Follow :

  1. Start writing code in an Java file.
  2. First let’s launch the browser (say using chrome here in the example).
  3. Enter the Application under test(AUT) url in the browser.

driver.get(“http://jqueryui.com/droppable/”);

  1. Maximize the browser window.

driver.manage().window().maximize();

  1. Lets first identify the xpath of Drag element and drop element.

WebElement dragLocator = driver.findElement(By.cssSelector(“#draggable”));

WebElement dropLocator = driver.findElement(By.cssSelector(“#droppable”));

  1. Create an object action class and pass the driver reference.

Actions action = new Actions(driver);

  1. Later use the predefined method of action to drag and drop the element from one position to another position.

dragAndDrop(source, destination)

  1. Lets completely build the drag and drop command with reference to action class(i.e action)

action.dragAndDrop(source, destination).build().perform();

  1. Finally close the browser window.
    driver.quit();

Code Snippet :

Leave a Comment

Your email address will not be published. Required fields are marked *