Scroll an element automatically using Selenium C# web driver

Nuthan Murarysetty
2 min readApr 17, 2019

--

As we all know, Scrolling happened either at Window or Element level. Most of all know how to do a window scroll using selenium C# and it will be automatically scrolled based on multiple X and Y values.

Now, When you get a requirement to scroll an element and this element scroll will behave the same as window scroll.

In general, We googled and find a solution for our problem from various web sites like StackOverflow, blogs, official websites for syntax and examples. If there is no proper solution to our problem then we are in a difficult situation to fix like how I faced it. In this article, I will show you how to scroll an element using Selenium C#.

Step 1: I am going to find an element using XPath

IWebElement webElement = webDriver.FindElement(By.Xpath(‘//*[@id=”Blog1"]/div[1]/div[1]/div/div/div/h3/a’));

Step 2: Get an Element Scroll Height, Scroll Width,Client Height, Client Width, X and Y cordinates

arguments[0].scrollWidth,arguments[0].scrollHeight, arguments[0].clientWidth,arguments[0].clientHeight

Step 3: To get the above values we use ExecuteScript method and get the above values.

int scrollWidth = (long)((IJavaScriptExecutor)webDriver).ExecuteScript(“arguments[0].scrollWidth”,webElement);

int scrollHeight = (long)((IJavaScriptExecutor)webDriver).ExecuteScript(“arguments[0].scrollHeight”,webElement);

int clientHeight= (long)((IJavaScriptExecutor)webDriver).ExecuteScript(“arguments[0].clientHeight”,webElement);

int clientWidth= (long)((IJavaScriptExecutor)webDriver).ExecuteScript(“arguments[0].clientWidth”,webElement);

int xCordinate = webElement.Location.X;

int yCordinate = webElement.Location.Y;

Step 4: Scroll an element using arguments[0].scrollBy(x,y)

((IJavaScriptExecutor)webDriver).ExecuteScript(“arguments[0].scrollBy(arguments[1],arguments[2]);”,webElement,x,y);

Where arguments[0] is webelement, arguments[1] is x and arguments[2] is y.

Note: To see scrolling effectively then pass multiple X and Y values.

I am hoping this article solved your problem. If so, just hit the like and clap buttons. Bye for now and catch you with another interesting article.

Happy Coding :)

--

--

Nuthan Murarysetty
Nuthan Murarysetty

Written by Nuthan Murarysetty

I love sharing things what I know to others and passionate in photography.

No responses yet