Performing drag-and-drop operations

Selenium WebDriver implements Selenium RC's dragAndDrop command using the Actions class. As seen in earlier recipes, the Actions class supports advanced user interactions such as firing various mouse and keyboard events. We can build simple or complex chains of events using this class.

In this recipe, we will use the Actions class to perform drag-and-drop operations.

How to do it...

Let's implement a test that will perform a drag-and-drop operation on a page using the Actions class:

@Test
public void testDragDrop() {
  driver.get("http://cookbook.seleniumacademy.com/DragDropDemo.html");

  WebElement source = driver.findElement(By.id("draggable"));
  WebElement target = driver.findElement(By.id("droppable"));

  Actions builder = new Actions(driver);
  builder.dragAndDrop(source, target) .perform();
  assertEquals("Dropped!", target.getText());
}

How it works...

To drag an element on to another element and drop it, we need to locate these elements and pass them to the dragAndDrop() method of the Actions class. To call this method, we need to create an instance of the Actions class in the following way:

Actions builder = new Actions(driver);

The dragAndDrop() method needs the source element and target element, where the source element will be dragged and dropped. We can call the dragAndDrop() method in the following way:

builder.dragAndDrop(source, target).perform();

Note

While writing this book, drag & drop for HTML5 was not supported by Selenium WebDriver. Please visit https://code.google.com/p/selenium/issues/detail?id=3604 for more details. There is a workaround available to simulate the drag & drop feature on HTML5 web applications. Visit https://gist.github.com/rcorreia/2362544 for more details.

See also

  • The Using Advanced User Interactions API for mouse and keyboard events recipe
  • The Performing double-click on an element recipe
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.88.62