public void scrollTo ( long position ) { String action = "Scrolling screen to " + position + " pixels above " + prettyOutput ( ) ; String expected = prettyOutputStart ( ) + " is now within the current viewport" ; try { // wait for element to be present if ( isNotPresent ( action , expected , CANT_SCROLL ) ) { return ; } // perform the move action JavascriptExecutor jse = ( JavascriptExecutor ) driver ; WebElement webElement = getWebElement ( ) ; long elementPosition = webElement . getLocation ( ) . getY ( ) ; long newPosition = elementPosition - position ; jse . executeScript ( "window.scrollBy(0, " + newPosition + ")" ) ; } catch ( Exception e ) { cantScroll ( e , action , expected ) ; return ; } isScrolledTo ( action , expected ) ; }
Scrolls the page to the element leaving X pixels at the top of the viewport above it making it displayed on the current viewport but only if the element is present . If that condition is not met the scroll action will be logged but skipped and the test will continue .