Ben
Ben

Reputation: 1

Determining if an element is visible on the computer screen using selenium c#

My main goal is to have the program scroll away from a specific element on the web page. I have tried using displayed or visible functions but they do not work. This is because displayed determines whether the element is displayed on the web page. I want a way to determine if the element is displayed on the actual computer screen. There is nothing wrong with identifying the element (using XPath in the example). My code:

IJavaScriptExecutor js = (IJavaScriptExecutor)driver;

IWebElement scroll = driver.FindElement(By.XPath("(//*[@class='_3ccb']/div[3])[1]"));

for (int p = 1; p < 1000; p++)
{

  if(scroll.Displayed == true)                                        
      js.ExecuteScript("window.scrollBy(0,-1)");

}

I want the program to see the element and scroll up until the element is off the actual computer screen, but it just scrolls up 1000 pixels.

Upvotes: 0

Views: 602

Answers (1)

jbob77435
jbob77435

Reputation: 187

You could use the elements Y coordinate instead with the scrollTo function, just remember to include the elements height:

var js = (IJavaScriptExecutor)driver;
var element= driver.FindElement(By.XPath("(//*[@class='_3ccb']/div[3])[1]"));

int yCoord = element.Location.Y;
int elementHeight = element.Size.Height;
int scrollAmount = yCoord + elementHeight;

js.ExecuteScript("window.scrollTo(0,"+ scrollAmount + ")");

This would scroll just past the element.

If you wanted it so the element was below the fold you'd need to subtract the browsers viewport height from the element's Y position instead. You can get the viewport height like this:

var viewPortHeight = jse.ExecuteScript("return Math.max(document.documentElement.clientHeight, window.innerHeight || 0)");

I hope this helps.

Upvotes: 1

Related Questions