1

I have a scroll into view already which works, however I was thinking to make it smarter.

This is my code so far

((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].scrollIntoView(true);", element);

which is hooked into my OnClicking event listener - so whenever it goes to click an element, first it scrolls it into view.

This is great and it does what I want it to, however when running my tests my page is scrolling up and down even if the element is in the middle of the screen.

So my question is, how do I set a parameter on this to say, if the element is below 3/4 on the viewable screen then scroll?

marwaha.ks
  • 540
  • 1
  • 7
  • 19

3 Answers3

1

I think. You can try it.

var element = driver.FindElement(By.Xpath("//*/blabla"));
var js = driver as IJavaScriptExecutor;
js.ExecuteScript("window.scrollTo(" + element.Location.X + ","+(element.Location.Y - 100) + ");");
Turgut Kanceltik
  • 639
  • 1
  • 8
  • 18
0

You can use javascript to get the X/Y cordinates:

var cumulativeOffset = function(element) {
    var top = 0, left = 0;
    do {
        top += element.offsetTop  || 0;
        left += element.offsetLeft || 0;
        element = element.offsetParent;
    } while(element);

    return {
        top: top,
        left: left
    };
};

In this case you want the Y coordinate. And use this: http://www.w3schools.com/jsref/met_win_scrollto.asp

Or... take a look at this: Javascript scrollIntoView() middle alignment?

Community
  • 1
  • 1
XorX
  • 238
  • 2
  • 5
  • 19
  • How do I use this with selenium? – marwaha.ks Oct 06 '16 at 12:42
  • Are you coding in Java? Php/Behat? Python? You can execute this as javascript. For java: https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/JavascriptExecutor.html – XorX Oct 06 '16 at 13:45
0

I know this is old post, but if people looking for answer, here it is

((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView({block: \"center\"});", webElement);