I'd like to check whether the user can see an element in the current web browser view without scrolling.
What I've found can check whether the element is somewhere on the page.
Another hint suggested to check the elements position but then I would need to get the dimensions of the visible window of the browser plus its x/y offset to 0/0.
I would be grateful if someone could point me to a solution that does not need JavaScript code.
Summary. Use the getBoundingClientRect() method to get the size of the element and its relative position to the viewport. Compare the position of the element with the viewport height and width to check if the element is visible in the viewport or not.
Another way to check if an element is hidden is to use the window. getComputedStyle() method. It will return the display property value of the object. We can check if the string is equal to none meaning the element is hidden and do something.
1. Select the element using QuerySelector var myvar= document. querySelector('ELEMENT'); 2. Check the OffsetWidth and Offsetheight to be greater than 0; (myvar.
How do you define 'visible to the user'? How do you propose to check it? If it has a height? If it isn't hidden by CSS? What if it's parent element is hidden by CSS?
The most reliable way will be to use Selenium's built in .Displayed
property (if you are using C#, Java has something similiar), and combine it with jQuery's 'visible' selector: http://api.jquery.com/visible-selector/. Example below, in C#.
var element = Driver.FindElement(By.Id("test"));
bool isVisible = element.Displayed;
var javascriptCapableDriver = (IJavascriptExecutor)Driver;
bool jQueryBelivesElementIsVisible = javascriptCapableDriver.ExecuteScript("return $('#myElement').is(:visible);");
bool elementIsVisible = isVisible && jQueryBelievesElementIsVisible;
This will get the majority of cases.
It isn't possible without client side code, or in the preparation that someone else finds a way that it can be done in a server side language, I highly doubt it will be pretty, readable or reliable.
jQuery has the offset()
method:
http://api.jquery.com/offset/
This, however, won't work when taking into account borders, margins, that kind of stuff.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With