how to drag and drop in selenium

To begin with, this tutorial will help you to perform drag and drop operations using Selenium. After completion of this tutorial, you will be able to drag one Web Element over another web element. Here we provide a detailed explanation of each step, snapshot, and code which not only helps you in understanding even helps you in writing your error-free code.
This tutorial specifically focused on drag and drop operation using Selenium. In other words, this tutorial provides end to end concept and helps you to write your drag and drop test.

How To Drag And Drop In Selenium – Selenium Drag and Drop Example in Java

Another key point is that the drag and drop feature makes the website very user-friendly hence it’s one of the frequent automation steps. To clarify, here are the two scenario’s which you need to automate:

Example 1: In this example, two blocks are given and you have to drag draggable elements over another element.

Before drag and Drop:

Drag & Drop Selenium Initial Position

After drag and drop operation:

Example 2: As an illustration, in this example, one draggable slider is given and you have to drag the slider to a specific position using Selenium.

Pre-requisite:

  1. Selenium set up with Testng should be done.

Set up Selenium & TestNG with Maven dependency

(If Selenium set up is not done then please check our this post – Selenium Installation Tutorial With Example

Also, read Selenium & TestNG setp with Maven Dependency to setup TestNG & Maven dependency in your selenium project


Actions in Selenium WebDriver

Available Methods details

Selenium actions class has two methods available for drag and drop operation.

Constructor Detail of Actions Class:

public Actions(WebDriver driver);

Sample object creation:

Actions action = new Actions(driver);


Method 1: dragAndDrop

public Actions dragAndDrop(WebElement source, WebElement target)

A convenience method that performs click-and-hold at the location of the source element, moves to the location of the target element, then releases the mouse.

Parameters:

source – element to emulate button down at.
target – element to move to and release the mouse at.

Method 2: dragAndDropBy

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

In another case, a convenience method that performs click-and-hold at the location of the source element, moves by a given offset, then releases the mouse.

Parameters:

source – element to emulate button down at.
xOffset – horizontal move offset.
yOffset – vertical move offset.

Method– build():

Equally important, this method generates a composite action containing all actions so far, ready to be performed (and resets the internal builder state, so subsequent calls to build() will contain fresh sequences).

Method– perform():

A convenience method for performing the actions without calling build() first.

public void perform() {
build().perform();
}

Here we go:

Step 1

Firstly, open Selenium Project and create one test class to write drag and Drop tests.

Step 2

Write code to Invoke Browser: We use WebDriverManager for browser binaries and made Chrome Browser instance for further use. This code is common for all the test methods so we are keeping this test under beforeTestSetUP and using Testng annotation @BeforeMethod. As we know @BeforeMethod code is executed before each testng method.

(For a more detailed explanation refer to our blog- Step by Step Selenium Installation Tutorial with Example

public class dragAndDropTest {
public static WebDriver driver = null;
@BeforeMethod public void beforeTestSetUP() { WebDriverManager.chromedriver().version("79.0").setup(); driver = new ChromeDriver(); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); }

Step 3

Create dragAndDropTest() method to write actual drag and drop operation.

@Test
public void dragAndDropTest(){ 
}

Step 4

Write Code to navigate drag and drop Page

driver.get(“https://jqueryui.com/resources/demos/droppable/default.html”)

  • Find xpath of draggable element(source element) and dropped element( target element) and store them as WebElement
WebElement dragableItem = driver.findElement(By.xpath("//div[@id='draggable']"));
WebElement droppableTargetElement = driver.findElement(By.xpath("//div[@id='droppable']"));
  • Make the object of Action Class
Actions action = new Actions(driver);// driver passed as constructor

Step 5

Use method drag and drop on the above object.

action.dragAndDrop(dragableItem, droppableTargetElement).build().perform();

Example 1 – testMethod:

@Test
public void dragAndDropTest() throws InterruptedException {
driver.get("https://jqueryui.com/resources/demos/droppable/default.html");
WebElement dragableItem = driver.findElement(By.xpath("//div[@id='draggable']"));
WebElement droppableTargetElement = driver.findElement(By.xpath("//div[@id='droppable']"));
Actions action = new Actions(driver);
action.dragAndDrop(dragableItem, droppableTargetElement).perform();
}

For example 2– draggable slider

public Actions dragAndDropBy(WebElement source, int xOffset, int yOffset)
xOffset - Xaxis postion where you want to slide
yOffset – Yaxis position where you want to slide
action.dragAndDropBy(dragableSlider, 250, 0).build().perform();

Example 2: Test Method code:

@Test
public void dragableSlider() throws InterruptedException {
driver.get("https://jqueryui.com/slider/");
//Given slider is in IFrame so we need switch in to Iframe first. Refer Iframe Blog for more understanding
WebElement iframe = driver.findElement(By.xpath("//iframe[@class='demo-frame']"));
driver.switchTo().frame(iframe);
WebElement dragableSlider = driver.findElement(By.xpath("//div[@id='slider']//span"));
Actions action = new Actions(driver);
action.dragAndDropBy(dragableSlider, 250, 0).build().perform();
Thread.sleep(5000);
}

Step 6

Write Code to close set after every Test Method. After each test, we will close the browser.

@AfterMethod public void closeSetUp() { 
if (!driver.equals(null)) { 
driver.quit(); 
} 
}

Complete Code:

package stepDef;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.concurrent.TimeUnit;
public class dragAndDropTest {
public static WebDriver driver = null;
@BeforeMethod public void beforeTestSetUP() { WebDriverManager.chromedriver().version("79.0").setup(); driver = new ChromeDriver(); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); 
}
 
@Test 
public void dragAndDropTest() throws InterruptedException { driver.get("https://jqueryui.com/resources/demos/droppable/default.html"); WebElement dragableItem = driver.findElement(By.xpath("//div[@id='draggable']")); 
WebElement droppableTargetElement = driver.findElement(By.xpath("//div[@id='droppable']")); 
Actions action = new Actions(driver); 
action.dragAndDrop(dragableItem, droppableTargetElement).perform(); 
} 
@Test 
public void dragableSlider() throws InterruptedException { driver.get("https://jqueryui.com/slider/"); 
//Given slider is in IFrame so we need switch in to Iframe first. Refer Iframe Blog for more understanding 
WebElement iframe = driver.findElement(By.xpath("//iframe[@class='demo-frame']")); 
driver.switchTo().frame(iframe); 
WebElement dragableSlider = driver.findElement(By.xpath("//div[@id='slider']//span")); 
Actions action = new Actions(driver); 
action.dragAndDropBy(dragableSlider, 250, 0).build().perform(); Thread.sleep(5000); 
} 
@AfterMethod 
public void closeSetUp() { 
if (!driver.equals(null)) { 
driver.quit(); 
} 
}

To conclude, check here the list of steps:

Summing up, below steps involved in the above tutorial :

  1. Open Browser
  2. Navigate to Drag and Drop Page
  3. Launch Browser
  4. Find draggable and dropable web Elements
  5. Make the object of Action class
  6. Use drag and drop(ordragAndDropBy) method followed by performing
  7. Lastly, close the browser.

Well done! Given these points, now you have completed the drag and drop operation using the Selenium Actions class. I hope you understand concepts well and able to use in your project. To this end, feel free to write us on query@thoughtcoders.com in case of any difficulty/feedback.

References:
https://www.selenium.dev/selenium/docs/api/java/org/openqa/selenium/interactions/Actions.html

Write A Comment