Reputation: 14943
I have several divs that are shown and hidden. How can I detect on a given element is it is currently visible on the page?
The element's style won't help, since it is a parent div
in the DOM that is being hidden.
Upvotes: 5
Views: 5233
Reputation: 3379
I have run into this issue before as well and I found the following to be the best solution:
Given an Element called "element":
boolean visible = UIObject.isVisible(element) && (element.getAbsoluteLeft() > 0) && (element.getAbsoluteTop() > 0);
The static "isVisible" method on UIObject will check for display none and that sort of thing, while the checks on the AbsoluteLeft and AbsoluteTop are there to handle detachment. The reason that I found the latter checks to be necessary was because if an element is detached from the DOM (and is hence not visible on the page) then GWT will still tell you that its visibility is true unless its visibility was explicitly set to false.
NB: You could replace the AbsoluteTop and AbsoluteLeft checks with the offset width and height checks as suggested by Simon, but you should include the isVisible check as well in my opinion.
Upvotes: 2
Reputation: 13237
If it's an Element, not a UIObject, the following worked for me:
!"hidden".equals(element.getStyle().getVisibility())
&& !"none".equals(element.getStyle().getDisplay())
I was walking down the tree, so knew the parent elements were visible; if your case is different, you'll probably need to do the same check on all parent elements.
Upvotes: 0
Reputation: 16079
You can have something like that:
public boolean isVisible(Widget w) {
while (w.getElement().hasParentElement()) {
if (w.isVisible()) {
return true;
}
w = w.getParent();
}
return w.isVisible();
}
Upvotes: 0
Reputation: 2987
Its offset height and width will both be 0.
UIObject component = ...
boolean isHidden = (component.getOffsetHeight() == 0 && component.getOffsetWidth() == 0);
Upvotes: 4