How to Drag and Drop in Selenium?

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. This tutorial provides a detailed explanation of each step, snapshot, and code which not only helps you in understanding even help you in writing your error-free code.
This tutorial specifically focused on drag and drop operation using Selenium. This tutorial provides end to end concept and helps you to write your drag and drop test.

Selenium Drag and Drop Example in Java

Drag and drop feature makes website very user friendly so it’s one of the frequent automation steps. 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: 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)

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():

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();
}

Step by Step Code and explanation: (Example 1)

  • Step 1: Create one Selenium Test Class: Open Selenium Project and create one test class to write drag and Drop test.
  • 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 method so we are keeping this test under beforeTestSetUP and use Testng annotation @BeforeMethod. As we know @BeforeMethod code is executed before each testng method.

(For more detailed explanation refer 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 dragAndDrop Page

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

  • Step 5: Find xpath of dragable 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']"));
  • Step 6: Make object of Action Class
Actions action = new Actions(driver);// driver passed as constructor
  • Step 7: Use method dragAndDrop on step 6 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- all the steps remains same except step 7

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 8: 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(); 
} 
}

List of steps:

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 dragAndDrop(ordragAndDropBy) method followed by perform
  7. Close browser.

Well done! Now you have completed drag and drop operation using Selenium Actions class. I hope you understand concepts well and able to use in your project. 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

Subscribe to our Newsletter:

0 0 vote
Article Rating
close

Subscribe to our Newsletter:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
Open chat
Feel free to contact