Sometimes, web elements require a double-click for action to perform certain operations. Selenium WebDriver provides the Actions class to handle advanced user interactions like double-clicking, right-clicking, dragging, and more. I have provided the script below to double click on element with selenium and java.
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.interactions.Actions;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class DoubleClickTest {
WebDriver driver;
@BeforeClass
public void setUp() {
// Set path to ChromeDriver
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
// Initialize WebDriver
driver = new ChromeDriver();
driver.manage().window().maximize();
// Open the target URL
driver.get("https://example.com");
}
@Test
public void testDoubleClick() throws InterruptedException {
// Locate the element to double-click
WebElement element = driver.findElement(By.id("elementId"));
// Create Actions instance
Actions actions = new Actions(driver);
// Perform double-click action
actions.doubleClick(element).perform();
// Optional: wait to observe the action
Thread.sleep(2000);
}
@AfterClass
public void tearDown() {
// Close the browser
if (driver != null) {
driver.quit();
}
}
}