Drag and drop activity performed by using Actions class.
- dragAndDrop(WebElement source, WebElement target) → It used to drag source element to target web element.
- dragAndDropBy(WebElement source, offsetX , offsetY) → It used to drag source web element to targeted location using offset.
Code snippet:
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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
import java.time.Duration; 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.chrome.ChromeOptions; import org.openqa.selenium.interactions.Action; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class SeleniumMain { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "D:/chromedriver.exe"); WebDriver driver; ChromeOptions cOptions=new ChromeOptions(); cOptions.addArguments("--start-maximized"); driver=new ChromeDriver(cOptions); driver.get("https://www.scribblemaps.com/create/"); //create object of Actions class Actions builder=new Actions(driver); //Create web element for close button on child pop up window WebElement closeButton = (new WebDriverWait(driver, 10)) .until(ExpectedConditions.presenceOfElementLocated(By.xpath("//div[@class='sm_panel sm_custom']/div[@class='sm_close']"))); //Perform click action builder.pause(Duration.ofSeconds(5)).moveToElement(closeButton).click().build().perform(); //create web element for shape tool object WebElement shapeToolObj=driver.findElement(By.xpath("//div[@class='sm_toolIcon sm_iso']/div")); //Perform click action builder.moveToElement(shapeToolObj).click().perform(); //get Car image WebElement sedanCar = (new WebDriverWait(driver, 10)) .until(ExpectedConditions.presenceOfElementLocated(By.xpath("(//div[@class='sm_isoIcon']/img)[1]"))); //Using offset for drag and drop Action moveCarOnMapByOffset=builder.dragAndDropBy(sedanCar,500 , 500).build(); //perform action moveCarOnMapByOffset.perform(); //Using WebElement for drag and drop WebElement map=driver.findElement(By.id("ScribbleMap")); Action placeCarOnMidOffMap=builder.dragAndDrop(sedanCar, map).build(); placeCarOnMidOffMap.perform(); //commented to see result //driver.quit(); } } |