Why do I get MoveTargetOutOfBoundsException in Selenium and how can I fix it?

I’m working with Selenium WebDriver on Windows 10 using Chrome version 105. I’m trying to automate a complex UI operation using the Actions class but keep getting a MoveTargetOutOfBoundsException. The script should scroll to a specific element and click it, but it seems like the element isn’t being scrolled into view. I expected the action to complete without errors, but it keeps failing at this point. I’ve tried adjusting my locator strategy and ensuring the element is visible, but no luck. How can I resolve this issue and ensure the element interacts as expected?

This exception usually occurs when Selenium tries to move the mouse to an element that is outside the visible viewport. If the element is not visible on the screen, the Actions class cannot interact with it and throws MoveTargetOutOfBoundsException.

A common solution is to scroll the element into view before performing the action.

Here is the snippet that worked for me:

WebElement element = driver.findElement(By.id("your-element-id"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);

Actions actions = new Actions(driver);
actions.moveToElement(element).click().perform();

By using scrollIntoView, the browser scrolls the page so the element becomes visible. Once it’s inside the viewport, Selenium can move to it and click successfully.

Also verify that your locator is correct and that the element is not hidden behind another element.

I encountered a similar problem while testing a responsive web application. In my case, the issue was related to the browser window size. When the viewport changed, elements shifted and sometimes ended up outside the visible area.

Setting a consistent window size helped stabilize the layout and made element interactions more reliable.

For example:

driver.manage().window().setSize(new Dimension(1200, 800));

WebElement element = driver.findElement(By.id("your-element-id"));
Actions actions = new Actions(driver);
actions.moveToElement(element, 0, 0).click().perform();

By fixing the window size, the page layout remains consistent and Selenium can correctly target the element.

Just be careful when relying on fixed coordinates, as they may behave differently on other screen resolutions.