Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@Max-Edwards 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

This comment has been minimized.

Copy link

@ccasalicchio ccasalicchio commented Apr 5, 2021

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