Skip to content

Instantly share code, notes, and snippets.

@nadvolod
Last active April 5, 2021 15:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nadvolod/2c5ce6c43b44fc2dc2a17cb34531597d to your computer and use it in GitHub Desktop.
Save nadvolod/2c5ce6c43b44fc2dc2a17cb34531597d to your computer and use it in GitHub Desktop.
How to scroll an element into a view using Selenium c#
element = driver.FindElement(By.LinkText("Click me using this link text!"));
//this will scroll the element and center it for interaction
var js = (IJavaScriptExecutor)Driver;
js.ExecuteScript("arguments[0].scrollIntoView({behavior: 'smooth', block: 'center'})", element);
//this one will scroll the element into view for interactions
IJavaScriptExecutor je = (IJavaScriptExecutor)driver;
je.ExecuteScript("arguments[0].scrollIntoView(false);", element);
@Max-Edwards
Copy link

Max-Edwards commented Mar 11, 2019

Hello,

I can not seem to get this to work. I am using Selenium (c#) version 3.141.0.

Also i has to make a change to line one of your code, this may be the cause of the issue:

var element = Driver.FindElement(By.XPath("//*[@id="slide-out"]/ul/div[2]/div"));

Should this still work?

@ccasalicchio
Copy link

For C# try this

        public void ScrollToId(string id)
        {
            this.Driver.ExecuteJavascript($"document.getElementById('{id}').scrollIntoView({{behavior: 'smooth', block: 'center'}});");
        }
        public static object ExecuteJavascript(this IWebDriver driver, string script)
        {
            return ((IJavaScriptExecutor)driver).ExecuteScript(script);
        }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment