1

I want to scroll to and element that is in the middle of the screen but not visible on the screen after navigating to the page. My tests are written with Selenium using C# language. Any advice is appreciated. Thanks!

I have tried to scroll to the element using class Actions but that doesn't work, probably because the element is not visible on the screen without scrolling.

Is a good approach to scroll using JavaScriptExecutor like this?

> IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
> js.ExecuteScript("arguments[0].scrollIntoView();", element);

And after this should I use the normal way of scrolling using Actions class?

> Actions actions = new Actions(driver);
> actions.MoveToElement(element);
> actions.Perform();
gabiO85
  • 13
  • 4
  • What do you do *after* scrolling to the element? Remember that Selenium and the web page execute independently of each other. Race conditions happen frequently. – Greg Burghardt Mar 15 '23 at 12:34
  • Did you try `.scrollIntoView()`? Did it work? If not, what error message did you get or describe how it didn't accomplish what you intended. – JeffC Mar 15 '23 at 17:53
  • Initially I tried to use the classical way from Selenium by using MoveToElement(element) method from the Actions class and than using the Perform() method. However this didn't work because the element had to be in the viewport in order for this to work. So I ended up using the Javascript method scrollIntoView() which I wanted to avoid in the first place...but looks like there is no other way in my case. @GregBurghardt after scroll I hover over an element in a graph so I again use the MoveToElement(element) method and Perform() :). – gabiO85 Mar 16 '23 at 13:26

1 Answers1

0

Using scrollIntoView() is definitely the best approach to bring the element within the Viewport.

However, before you attempt to scroll the element you need to induce WebDriverWait for the ElementIsVisible() as follows:

IWebElement element = new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementIsVisible(By.XPath("ElementXPath")));
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
js.ExecuteScript("arguments[0].scrollIntoView();", element);
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
  • 1
    Thank for the suggestion, indeed this is the way in which I implemented it in my case also. Initially I wanted to not use JavaScript code but as it turns out there is no other way in case the element is not displayed in the viewport. – gabiO85 Mar 16 '23 at 13:29