Search code examples
grailsspockgeb

How to check if element is visible in viewport?


If I am at the bottom of the page how can I check if some element is visible if that element is for example at the top of the page.

I need to write a test where I scroll down to the bottom of the page and when I click on div it moves me back to the top of the page. Next step is to check if I am at that position. My idea was that I just need to check if that element is visible but it turns out that it is not that easy to do. Any suggestions?

.isDisplayed() and .isFocused() is not what I need.

Edit: I had an idea and I need two methods for it.

First one is to get y coordinate of the element (we need only y), but the problem is that getY() returns number relative to your current position, so I need something that will move me to that element and then get y coordinate. So my method looked something like this:

int getYCoordinat() {
        // first move to the element
        interact {
            moveToElement(element)
        }
        // get y coord
            return element.getY()
    }

second method looked something like this:

boolean isScrolledToElement(int yCoordinateOfElement) {
            int y = element.getY()
            return y == yCoordinateOfElement
        }
    }

So first I would call getYCoordinat(), store integer into yCoordinateOfElement. Then I would click on div that moves me to the element and call isScrolledToElement(yCoordinateOfElement).

But it doesnt work because moveToElement moves you to that element only if the element is not visible. So if we stay where we are because moveToElement() didn't move us, because element is already visible, we get the wrong Y coordinate that won't be same as the one which we get when we click on div that moves us to the element.


Solution

  • Here is the only solution I could find. Basically you need to see if the pixel coordinate of the bottom-right corner of your element is within the window.

    Taken from the link:

    private boolean isWebElementVisible(WebElement w) {
        Dimension weD = w.getSize();
        Point weP = w.getLocation();
        Dimension d = driver.manage().window().getSize();
    
        int x = d.getWidth();
        int y = d.getHeight();
        int x2 = weD.getWidth() + weP.getX();
        int y2 = weD.getHeight() + weP.getY();
    
        return x2 <= x && y2 <= y;
    }