Cypress scrollIntoView Command

Profile picture for user arilio666

Cypress scrollIntoView command scrolls to the element's parent container so that element is visible to the user. scrollIntoView() yields the same subject it was given from the previous command.

Syntax

.scrollIntoView()
.scrollIntoView(options)

Arguments Used in ScrollIntoView:

We can pass an options object and change the behavior of .scrollIntoView()

  • Duration: This option scrolls over duration in ms, and the default value is 0.
  • Easing: This option will scroll with an easing animation, and the default value is swing. Other accepted value is linear.
  • Log: Displays commands in the command log, and the default value is true.
  • offset: Amount to scroll after the element has been scrolled into view and the default value is {top: 0, left: 0}
  • Timeout: This option is used to wait for the scroll to resolve before timing out.

Rules for using scroll Into View

  1. scrollIntoView requires being chained off a command which yields a DOM element. It can not be chained off with Cy or Window().
  2. scrollIntoView automatically waits for assertions you have chained to pass.
  3. scrollintoview can also timeout waiting for assertions added to pass.

Example: Scroll into View Before Click

For real-time example purposes, we will be using the automation practice website and we will jump to Best Seller tab and click on it.

cypress scroll into view

Below code will scroll with easing and duration 5 seconds and click on Best Seller.

it.only('scroll', () => {
    cy.visit('http://www.automationpractice.com/')
    cy.get('a.blockbestsellers').scrollIntoView({easing: 'linear', duration: 5000}).click()
})

 

Cypress scroll into view and click

Example: Scroll in to view with offset

cy.get('a.blockbestsellers').scrollIntoView({
    easing: 'linear',
    duration: 5000,
    offset: { top: 100, left: 0 },
})

scroll in to view with offset

Observer that Popular and Best Seller not showing in view it scrolled 100 pixel down from Best Seller.