Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if an element is really visible to the user

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.

like image 213
user1882216 Avatar asked Dec 06 '12 11:12

user1882216


People also ask

How do you check if an element is visible to the user?

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.

How do you check if an HTML element is hidden?

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.

How do you check if an element is visible on the web page Javascript?

1. Select the element using QuerySelector var myvar= document. querySelector('ELEMENT'); 2. Check the OffsetWidth and Offsetheight to be greater than 0; (myvar.


1 Answers

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.

like image 62
Arran Avatar answered Sep 29 '22 12:09

Arran