Skip to main content

Cypress scrollIntoView Command

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.

    Video Tutorial: Cypress Scroll Into View

    Tags
    Submitted by arilio666 on May 27, 2022

    Ashwin is working with iVagus as a Technical Lead. He has experience in various technologies like Cypress, JavaScript, TypeScript, Rest Assured, Selenium, Cucumber, and Java.

    About

    At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.