Playwright Hover Over Element

Profile picture for user arilio666

In Playwright, we use the hover() method to hover over an element. This method can be used with page instances and with the locator method. However, the playwright team recommends using the locator-based hover() method. You will see a warning on the page.hover() documentation page. It will scroll the element into view if needed.

Table of Contents

  1. Syntax
  2. Demo Website
  3. Example
  4. Video Tutorial

Syntax:

await locator.hover();
await locator.hover(options);

Options: Object (optional)

  • force: boolean (optional) -  Default value is false. We can set it to true to bypass the actionability checks. When it is false or by default, hover() will wait for actionability checks on the element. 
  • modifiers: Array<"Alt"|"Control"|"Meta"|"Shift"> (optional)  - Using this option, we can specify modifier keys to press. If not specified, currently pressed modifiers are used.
  • noWaitAfter: boolean (optional) - Default value is false, and the hover() command waits for initiated navigations to either succeed or fail. We can opt-out of waiting by setting this flag to true.
  • positions: Object (optional): By default, hover() use page.mouse property to hover over the center of the element. Otherwise, you can give positions x and y.
  • timeout: number (optional) - Time in milliseconds. Maximum time 30 seconds. Set it to 0 to disable the timeout. The default value can be changed using different methods.
  • trail: boolean (optional) - Default value is false. When set, this method only performs the actionability checks and skips the action. Useful to wait until the element is ready for the action without performing it. 

Demo Website:

For the demo, visit the home page of the autopract website and mouse hover on any image in the Top Collection section. You will see Cart and a few other icons on mouse hover. Let's click on the cart icon. 

how to mouse hover in playwright

Example: Mouse Hover and Click

test.only('Hover Element', async ({page})=> {
    await page.goto("http://autopract.com")
    
    // Close popup display on opening website
    await page.locator("button.close").click()
    
    // hover on product section
    await page.locator("app-product-box-one").first().hover()
    
    // Click on cart icon
    await page.locator("app-product-box-one i.ti-shopping-cart").first().click()
}) 

Video Tutorial: Playwright Hover Over Element