Is there any way to scroll an element to the middle of the screen? I tried:
((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView();", element);
But it always scrolls on the top.
Is there any way to scroll an element to the middle of the screen? I tried:
((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView();", element);
But it always scrolls on the top.
The scrollIntoView()
method scrolls the specified element into the visible area of the browser window.
Syntax :
element.scrollIntoView(alignTo)
Parameters :
alignTo(Boolean) : An optional parameter where :
true
: the top of the element will be aligned to the top of the visible area of the scrollable ancestor
false
: the bottom of the element will be aligned to the bottom of the visible area of the scrollable ancestor.
skipped
: it will scroll to the top of the element.
Note : Depending on the layout of other elements, some elements may not be scrolled completely to the top or to the bottom.
As per your usecase as you want to scroll element to the middle of the screen instead of using scrollIntoView()
as an alternative you can scroll the window using either of the following options :
scroll()
((JavascriptExecutor)driver).executeScript("scroll(0, 250);");
window.scrollBy()
((JavascriptExecutor)driver).executeScript("window.scrollBy(0,250)", "");
As I can see this question already have some good answers, But there are many ways you can do scroll Down/scroll up in selenium. out of all those ways I would like to add one more to this question.
You can use Action class for this purpose :
Code
Actions action = new Actions(driver);
action.sendKeys(Keys.PAGE_DOWN).build().perform();
you can call sendKeys(Keys.PAGE_DOWN)
multiple times as per your requirement. Like this :
action.sendKeys(Keys.PAGE_DOWN).sendKeys(Keys.PAGE_DOWN).build().perform();
and so on !
One of the other way is go with JavaScript. @Ishita Shah have already provided that solution.
Try this :
driver.findElementByAndroidUIAutomator("new UiScrollable(new UiSelector()).scrollIntoView(new UiSelector().text(\"Text of element upto which you want to scroll down\"));");
You can scroll according to Web Page sections,
If you wants to scroll web page, by middle. It means go for bottom position up to required:
Syntax:
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(0,200)");
It will scroll vertically down.
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].scrollIntoView({block: 'center', inline: 'nearest'});");