Site icon

Drag & Drop – Actions Class in Selenium WebDriver Java

Must Read:  Handle mouse & keyboard events in Selenium (Actions class).

Actions class provides two methods for handling drag & drop:

Code : Drag & Drop using dragAndDrop(Sourcelocator, Destinationlocator):

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.Test;		

public class DragAndDrop {				

    WebDriver driver;			

    @Test		
    public void DragAndDropTest()					
    {		
         System.setProperty("webdriver.chrome.driver","C://chromedriver.exe ");					
         driver= new ChromeDriver();					
         driver.get("Enter the URL of the Website");					
         
		//Element needs to drag.    		
        	WebElement sourceElement =driver.findElement(By.xpath("enter xpath here"));	
         
         //Element on which need to drop.		
         WebElement targetElement =driver.findElement(By.xpath("enter xpath here"));					
         		
         // Create object of Actions class for drag and drop.		
         Actions actions = new Actions(driver);					

	     //Drag and drop method.		
         actions.dragAndDrop(sourceElement, targetElement ).build().perform();		
	}		
}

Code : Drag & Drop using dragAndDropBy(source, xOffset, yOffset):

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.Test;

public class DragAndDrop {

	WebDriver driver;

	@Test
	public void DragAndDropTest() {
		System.setProperty("webdriver.chrome.driver", " C://chromedriver.exe ");
		driver = new ChromeDriver();
		driver.get("Enter the URL of the Website");

		// Element needs to drag.
		WebElement sourceElement = driver.findElement(By.xpath("enter xpath here"));

		// Create object of Actions class for drag and drop.
		Actions actions = new Actions(driver);

		// Drag and Drop by Pixel
		actions.dragAndDropBy(sourceElement, 150, 50).build().perform();
	}
}
Exit mobile version