How to perform the Drag And Drop action


#1

dragAndDrop() Action

Some web applications have the functionality to drag web elements and drop them on a defined area or element. We can automate drag and drop of such elements using Selenium Webdriver.

There are a few different ways that make automating drag and drop possible.
In the following example, we will use the Actions.dragAndDrop(sourceLocator, destinationLocator).

In the dragAndDrop method, we pass the two parameters:
First parameter - “WebElement source” is the element which we need to drag.
Second parameter - “WebElement target” is the element on which we need to drop the source element.

Workflow:

  • Define and generate the source and target WebElements. Use Ranorex Selocity to quickly generate desired selectors

    WebElement source = this.wait.until(ExpectedConditions.visibilityOfElementLocated(this.DragMe));
    WebElement target = this.wait.until(ExpectedConditions.visibilityOfElementLocated(this.DropHere));
    
  • Instantiate action class

    Actions act = new Actions(driver);
    
  • Perform the dragAndDrop action

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

    The whole action step would look like this:

     public itemsPo dragAndDrop() {
    
          // Locate the elements
          WebElement sourceElement = this.wait.until(ExpectedConditions.visibilityOfElementLocated(this.source));
          WebElement targetElement = this.wait.until(ExpectedConditions.visibilityOfElementLocated(this.target));
    
          // Instantiate the Actions class
          Actions act = new Actions(driver);
    
          // Perform the dragAndDrop() method
          act.dragAndDrop(sourceElement, targetElement).perform();
    
          return this;
      }
    

    Or as a one-liner:

    (new Actions(driver).dragAndDrop(source, target)).perform();
    

Another way to perform the dragAndDrop action is the dragAndDropBy(source, xOffset, yOffset) method. Here we have 3 parameters:

  • source (WebElement) - the element on which we are performing the action
  • xOffset (Integer) - horizontal move offset
  • yOffset (Integer) - vertical move offset

So if we would like to drag an element to a specific location, for example, 100 px horizontally and 50px vertically we can use this approach:

(new Actions(driver).dragAndDrop(source, 100, 50)).perform();

Check out this article to find out more about using the Actions class in Ranorex Webtestit!