Perform drag and drop of elements

In this post we will see how to perform drag and drop operation on elements in selenium webdriver.

We will take an example of the website ‘http://jqueryui.com/droppable’.

Here we can see 2 elements on above link. One element is draggable which is called the Source element. It will be dragged from one location and dropped in another location which is called Target.

Drag and Drop using selenium webdriver

Following code performs the drag and drop operation on these elements.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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.Actions;

public class DragAndDropDemo {

 public static void main(String[] args) {

  System.setProperty("webdriver.gecko.driver", "./Myproject/driver/geckodriver.exe");
  WebDriver driver = new FirefoxDriver();
 
  driver.get("http://jqueryui.com/droppable");
  driver.manage().window().maximize();
  
  Actions act = new Actions(driver);

  // Script for dragging an element and dropping it in another place
  WebElement iFrame = driver.findElement(By.tagName("iframe"));

  System.out.println(iFrame.getSize());
  
  driver.switchTo().frame(iFrame);
  
  WebElement From = driver.findElement(By.id("draggable"));
  System.out.println(From.getLocation());
  
  WebElement To = driver.findElement(By.id("droppable"));
  System.out.println(To.getLocation());
  
  act.dragAndDrop(From, To).build().perform();
 }
}



<-- Previous || Next -->

No comments:

Post a Comment