How simple drag and drop work

Posted on

For a Drag and Drop you need a source element and a destination element. Let's consider one of the example of our demo website. Click on this link to access the drag and drop demo website.

Step 1 : Get source element

In this example the source element is in a unordered list. Here we need to select each item as source element and drop it to the destination element. Also we do not have any unique identifier for each source item. What we have here is ID for ul tag which is parent element of li. Hence we have to use either XPath or CSS Selector. Let's use following XPath.

XPATH : //ul[id='sourceElem']/li[1]
HTML
Copy
<ul id="sourceElem" class="connectedSortable ui-sortable">
   <li class="ui-state-default ui-sortable-handle">Item 1</li>
   <li class="ui-state-default ui-sortable-handle">Item 2</li>
   <li class="ui-state-default ui-sortable-handle">Item 3</li>
   <li class="ui-state-default ui-sortable-handle">Item 4</li>
   <li class="ui-state-default ui-sortable-handle">Item 5</li>
</ul>

Step 2 : Get destination element

Similar the case for the destination element. Here we have ID for ul tag. Hence we will use XPath. Let's use following XPath.

XPATH : //ul[id='destinationElem']
HTML
Copy
<ul id="destinationElem" class="connectedSortable ui-sortable">
   <li class="ui-state-default ui-sortable-handle">Item 1</li>
   <li class="ui-state-default ui-sortable-handle">Item 2</li>
   <li class="ui-state-default ui-sortable-handle">Item 3</li>
   <li class="ui-state-default ui-sortable-handle">Item 4</li>
   <li class="ui-state-default ui-sortable-handle">Item 5</li>
</ul>

Step 3 : Put everything in code

Since we have identified the XPath for the both source element and destination element, let's put everything in Java Code.
Java
Copy
WebDriver wd = new ChromeDriver();
wd.get("https://www.testautomationstudio.com/studio/actions/");
wd.manage().window().maximize();
wd.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
WebElement sourceElem = wd.findElement(By.xpath("//ul[id='sourceElem']/li[1]"));
WebElement destinationElem = wd.findElement(By.xpath("//ul[id='destinationElem']"));
Actions dragDropAction = new Actions(driver);
dragDropAction.dragAndDrop(sourceElem, destinationElem).build().perform();
In the above code we have created an object of action class and used it's method dragAndDrop with source and destination web element as parameter to drag and drop the item from source element to destination element.