Javascript scroll to element and click the element using java script as locator as xpath in Webdriver.
Imagine a scenario where you want locate an element using xpath and to scroll to the element and click on it using Java script .
In such a case , you can use below code .
package com.webdriver.blogs;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class ScrollUsingJavaScriptWebdriver {
WebDriver driver;
@BeforeClass()
public void setUp() {
System.setProperty(“webdriver.chrome.driver”,System.getProperty(“user.dir”)+”\\Jar_files\\chromedriver.exe”);
ChromeOptions options = new ChromeOptions();
options.addArguments(“start-maximized”);
driver = new ChromeDriver(options);
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driver.manage().window().maximize();
}
@Test(priority=1,enabled=true,description=”Scroll to element using Javascript”)
public void scrollToELement() throws InterruptedException {
String url=”https://www.globalsqa.com/demo-site/";
//Define a js object with type of JavascriptExecutor class and here the TypeCasting is applied
JavascriptExecutor js = (JavascriptExecutor) driver;
//The url is parameterized and \ \ signs are optional and This is similar to driver.get(“https://www.bbc.com/");
js.executeScript(“window.location = \’”+url+”\’”);
WebElement element = driver.findElement(By.xpath(“//div[@id=\”post-2715\”]/div[3]/a”));
//Scroll to the element
((JavascriptExecutor)driver).executeScript(“arguments[0].scrollIntoView();”, element);
//Click on the element using javascript and locator as xpath
((JavascriptExecutor)driver).executeScript(“arguments[0].click();”, element);
}
@AfterClass()
public void shutDown() {
driver.close();
driver.quit();
}
}