How to hover over an element in Selenium Webdriver?

Hovering over an element is a common scenario when automating a web application. For E.g. info is shown as a tooltip after hovering over an element. So, this post will discuss how we can automate such scenarios where hovering is required on elements.

We will use the below-highlighted element on our selenium playground website – https://testkru.com/Elements/Buttons.

"Hover on me" button element

Actions class provides a moveToElement() method that moves a mouse pointer to the middle of the specified element. This simulates the hover behaviour for the web element, so we will use it to hover over the highlighted element.

Hovering over an element is a simple 2-step process.

  • Find the web element onto which we want to hover.
  • And then use the moveToElement() method on it.

If we inspect the highlighted element, we can see the id attribute value is “colorChangeOnHover“. We can use it to find the element using the findElement() method.

WebElement webElement = driver.findElement(By.id("colorChangeOnHover"));

And after locating the element, we can use the moveToElement() method to hover over it.

Actions actions = new Actions(driver);
actions.moveToElement(webElement).build().perform();
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

public class CodekruTest {

	public static void main(String[] args) {

		// pass the path of the chromedriver location in the second argument
		System.setProperty("webdriver.chrome.driver", "E:\\chromedriver.exe");
		WebDriver driver = new ChromeDriver();

		driver.get("https://testkru.com/Elements/Buttons");

		WebElement webElement = driver.findElement(By.id("colorChangeOnHover"));

		Actions actions = new Actions(driver);
		actions.moveToElement(webElement).build().perform();

	}

}

The above code will hover over the element, and its color will change to show that we are hovering over it.

Hover on the button

We hope that you have liked the article. If you have any doubts or concerns, please write to us in the comments or mail us at admin@codekru.com.

Related Articles
Liked the article? Share this on

Leave a Comment

Your email address will not be published. Required fields are marked *