'What is the difference between the different scroll options?

I have tried a few ways of adding scrolling to tables, but just one of them works correctly. What is the different between them?

First:

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].scrollIntoView();", Element);

Second:

WebElement element1 = driver.findElement(By.id("scrolled_element"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element1);

Third:

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(0,1000)");

Fourth:

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollTo(0, document.body.scrollHeight)");


Solution 1:[1]

I'll put the relevant documentation below each example so that you can refer to it yourself, and give some of my very humble opinions:


.scrollIntoView() vs .scrollIntoView(true)

https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView

There shouldn't be a difference since the documentation states that by default, .scrollIntoView() actually has a default value of true.


.scrollBy()

https://www.w3schools.com/jsref/met_win_scrollby.asp

Scrolls the document by the indicated pixels. Meaning if your top left viewport is at (10,10), doing a .scrollby(5,6) means the viewport will, after shifting, be at a pixel coordinate of (15,16).


.scrollTo()

https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollTo

Does what it suggests -- i.e. scrolls to the coordinates you have provided. This is different to scroll by (i.e. above example). This means that .scrollTo(1,1) will scroll the document so that your top-left viewport is now at a pixel coordinate of (1,1), regardless of what it was before.


To your separate question of what are the total scroll options -- well, there's also window.scroll(), but based on the below SO article there shouldn't be any difference to scrollTo():

JavaScript window.scroll vs. window.scrollTo?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Arad