Selenium C# – JavaScript ScrollToView

Selenium C# – JavaScript ScrollToView
Introduction
In Selenium automation, there are moments when you need to scroll to a specific element before you can interact with it. JavaScriptExecutor in Selenium helps you do just that by scrolling the element into view, ensuring it's visible and ready to go. In this guide, we'll walk you through how to use JavaScript to scroll to an element using Selenium in C#.
Code Implementation
Below is a C# Selenium script that opens a browser, navigates to a demo website, clicks a link, and scrolls to a specific element using JavaScriptExecutor.
Example: JavaScript ScrollToView with Selenium in C#.
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Interactions;
using OpenQA.Selenium.Support.UI;
using SeleniumExtras.WaitHelpers;
using System.Globalization;
namespace SACSSAuto.QA.SeleniumPractice
{
[TestClass]
public class Selenium_76
{
/****
* Sample Code Definition :- Selenium - JavaScript ScrollToView
* Developed By :- Pankaj Kumar
* Date of Creation :- 31-Jan-2025
* Project :- SACSSAUTO - C# [Web / Mobile / API] *
*/
[TestMethod]
public void Selenium_Test()
{
Console.WriteLine("Selenium - JavaScript ScrollToView");
// Open Chrome Browser
IWebDriver driver = new ChromeDriver();
// Maximize the Browser Window
driver.Manage().Window.Maximize();
// Open the URL
driver.Navigate().GoToUrl("https://practice.solveautomation.in");
// Wait for 5 seconds
Thread.Sleep(5000);
//Click the Register Link
driver.FindElement(By.XPath("//a[normalize-space()='Register']")).Click();
// Wait for 5 Seconds
Thread.Sleep(5000);
// Click on Element By using JavaScript
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
IWebElement elem = driver.FindElement(By.XPath("//a[normalize-space()='SolveAutomation.in']"));
js.ExecuteScript("arguments[0].scrollIntoView(true);", elem);
// Wait for 5 seconds
Thread.Sleep(5000);
// Quit the driver
driver.Quit();
}
}
}
Steps Explained
1. Navigating to the Target Page
The browser opens the practice site and clicks the "Register" link.
2. Scrolling to Element
JavaScriptExecutor scrolls to a specific link labeled "SolveAutomation.in".
3. Wait and Exit
After scrolling, the script waits briefly and closes the browser session.
Expected Outcome
Opens the practice website.
Navigates to the Register page.
Scrolls to the "SolveAutomation.in" link.
Closes the browser session.
Conclusion
Using JavaScriptExecutor's scrollIntoView(true)
method makes it easy to scroll to elements in Selenium automation. This method helps ensure that elements are visible and ready to interact with, which is especially handy for dynamic or long web pages where elements might be out of view.
Subscribe to my newsletter
Read articles from Pankaj Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
