Handling different Scroll types using selenium Webdriver_Selenium online Training

In this post, I am going to explain how can we handle scroll of webpage using selenium webdriver with help of JavascriptExecutor interface.

Here we can use either scroll(x,y) or window.scrollBy(x,y).Both x and y are coordinates of webpage.

Vertical Scroll Down :
Sample code :
      //Creating instance of Javascript executor
       JavascriptExecutor jse = (JavascriptExecutor)driver;
       jse.executeScript("window.scrollBy(0,250)", "");

Vertical Scroll Up:
Sample code :
      //Creating instance of Javascript executor
       JavascriptExecutor jse = (JavascriptExecutor)driver;
       jse.executeScript("window.scrollBy(0,-250)", "");

Scroll To specific Element:
Sample code :
      // specific Web element
      WebElement wb = driver.findElement(By.xpath("//button[@name='submit']"));
      //Creating instance of Javascript executor
       JavascriptExecutor jse = (JavascriptExecutor)driver;
       jse.executeScript("arguments[0].scrollIntoView(true);",wb);

Horizontal Scroll Right:
Sample code :
      //Creating instance of Javascript executor
       JavascriptExecutor jse = (JavascriptExecutor)driver;
       jse.executeScript("window.scrollBy(3000,0)", "");

Horizontal Scroll Left:
Sample code :
      //Creating instance of Javascript executor
       JavascriptExecutor jse = (JavascriptExecutor)driver;
       jse.executeScript("window.scrollBy(-3000,0)", "");