views:

10534

answers:

13

In javascript, how would you check if an object is actually visible. I don't just mean checking the visibility and display attributes. I mean, checking that the element is not

  • visibility:hidden or display:none
  • underneath another element
  • scrolled off the edge of the screen.

EDIT: For technical reasons, I can't include any scripts. I can however use prototype as it is on the page already.

EDIT 2: This is no longer neccesary, but I'd still find an answer interesting)

A: 

I'd hate to redirect you to jQuery (like often is done) But this discussion about when elements are really visible is very insightful.

And since jQuery 1.3.2 this is no longer a problem

Ólafur Waage
That solves the first part and the third part but what about the second? How to tell if it's beneath another element.Also, for technical reasons, I can't use jQuery, or any other includes, although Prototype is available already.
Macha
@TonyF: jQuery 1.3.2 does what @Sergey suggested, which is to check the dimensions of the element (elements that are not part of the rendering flow have no dimension). This covers half of 1) and neither 2) nor 3), so is fairly useless to what it seems you need.
Crescent Fresh
+2  A: 

Check elements' offsetHeight property. If it is more than 0, it is visible. Note: this approach doesn't cover a situation when visibility:hidden style is set. But that style is something weird anyways.

Sergey Ilinsky
So this covers half of 1) and neither 2) nor 3).
Crescent Fresh
+1  A: 

Prototype's Element library is one of the most powerful query lib in terms of the methods. I recommend you to check out the API.

A few hints:

1) Checking visibility can be a pain but you can use the Element.getStyle() method and Element.visible() method combined into a custom function. With getStyle() you can check the actual computed style.

2) I don't know exactly what you mean by "underneath" :) If you meant by it has a specific ancestor eg. a wrapper div, you can use Element.up(cssRule):

var child = $("myparagraph");
if(!child.up("mywrapper")){
  // i lost my mom!
} else {
  // i found my mom!
}

If you want to check the siblings of the child element you can do that too:

var child = $("myparagraph");
if(!child.previous("mywrapper")){
  // i lost my bro!
} else {
  // i found my bro!
}

3) Again, Element lib can help you if I understand correctly what you mean :) You can check the actual dimensions of the viewport and the offset of your element so you can calculate if your element is "off screen".

Good luck!

Update: I pasted a test case for prototypejs here http://gist.github.com/117125 It seems in your case we simply cannot trust in getStyle() at all. For maximize the reliability of the isMyElementReallyVisible function you should combine the following:

  • checking the computed style (dojo has a nice implementation that you can borrow)
  • checking the viewportoffset (prototype native method)
  • checking the z-index for the "beneath" problem (under IE it may be buggy)
yaanno
I think I misunderstood the question completely. You want to be sure your element is visible in the viewport no matter what right?
yaanno
1 and 3 are fine. You misunderstood 2. I have a few elements that are free to move around the screen. The element in question would be underneath another element if say a user dragged a toolbox over on top of it.
Macha
To clarify my last point, the toolbox would be a div inside the body, while the element could be a few levels deep.
Macha
A: 

Catch mouse-drag and viewport events (onmouseup, onresize, onscroll).

When a drag ends do a comparison of the dragged item boundary with all "elements of interest" (ie, elements with class "dont_hide" or an array of ids). Do the same with window.onscroll and window.onresize. Mark any elements hidden with a special attribute or classname or simply perform whatever action you want then and there.

The hidden tests are pretty easy. For "totally hidden" you want to know if ALL corners are either inside the dragged-item boundary or outside the viewport. For partially hidden you're looking for a single corner matching the same test.

SpliFF
A: 

This is what I have so far. It covers both 1 and 3. I'm however still strugling with 2 since I'm not that familiar with Prototype (I'm more a Jquery type of guy).

function isVisible( elem ){
 var $elem = $(elem);
 //First check if elem is hidden through css as this is not very costly:
 if($elem.getStyle('display') == 'none' || $elem.getStyle('visibility') == 'hidden' ){
  //elem is set through CSS stylesheet or inline to invisible
  return false;
 }
 //Now check for the elem being outside of the viewport
 var $elemOffset = $elem.viewportOffset();
 if($elemOffset.left < 0 || $elemOffset.top < 0){ 
        //elem is left of or above viewport
  return false;
 }
 var vp = document.viewport.getDimensions();
 if($elemOffset.left > vp.width || $elemOffset.top > vp.height){ 
        //elem is below or right of vp
  return false;
 }
 //Now check for elements positioned on top:
 //TODO: build check for this using prototype...
 //Neither of these was true, so the elem was visible:
 return true;
}
Pim Jager
+1  A: 

Interesting question.

This would be my approach.

  1. At first check that element.style.visibility !== 'hidden' && element.style.display !== 'none'
  2. Then test with document.elementFromPoint(element.offsetLeft, element.offsetTop) if the returned element is the element I expect, this is tricky to detect if an element is overlapping another completely.
  3. Finally test if offsetTop and offsetLeft are located in the viewport taking scroll offsets into account.

Hope it helps.

SleepyCod
Could you explain document.elementFromPoint in more detail?
Macha
this is Mozilla's MDC summary :Returns the element from the document whose elementFromPoint method is being called which is the topmost element which lies under the given point. The point is specified via coordinates, in CSS pixels, relative to the upper-left-most point in the window or frame containing the document.
SleepyCod
A: 

can you make a change to the element that would trigger a reflow IF the element were visible BUT NOT IF the element were not visible?

+9  A: 

@Macha:

For the point 2.

I see that no one has suggested to use document.elementFromPoint(x,y), to me it is the fastest way to test if an element is nested or hidden by another. You can pass the offsets of the targetted element to the function.

Here's PPK test page on elementFromPoint.

SleepyCod
Thanks. That was the hardest part.
Macha
Isn't that a IE only solution ?
e-satis
@e-satis: It works in Firefox for me. It doesn't work in Opera.
Macha
I must admit I had no idea about that method. Thanks for sharing. +1
Ionuț G. Stan
A: 

Here is a sample script and test case. Covers positioned elements, visibilty: hidden, display: none. Didn't test z-index, assume it works.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt;
<html>
  <head>
    <title></title>
    <style type="text/css">
    div {
      width: 200px;
      border: 1px solid red;
    }
    p {
      border: 2px solid green;
    }
    .r {
      border: 1px solid #BB3333;
      background: #EE9999;
      position: relative;
      top: -50px;
      height: 2em;
    }
    .of {
      overflow: hidden;
      height: 2em;
      word-wrap: none; 
    }
    .of p {
      width: 100%;
    }

    .of pre {
      display: inline;
    }
    .iv {
      visibility: hidden;
    }
    .dn {
      display: none;
    }
    </style>
    <script src="http://www.prototypejs.org/assets/2008/9/29/prototype-1.6.0.3.js"&gt;&lt;/script&gt;
    <script>
      function isVisible(elem){
        if (Element.getStyle(elem, 'visibility') == 'hidden' || Element.getStyle(elem, 'display') == 'none') {
          return false;
        }
        var topx, topy, botx, boty;
        var offset = Element.positionedOffset(elem);
        topx = offset.left;
        topy = offset.top;
        botx = Element.getWidth(elem) + topx;
        boty = Element.getHeight(elem) + topy;
        var v = false;
        for (var x = topx; x <= botx; x++) {
          for(var y = topy; y <= boty; y++) {
            if (document.elementFromPoint(x,y) == elem) {
              // item is visible
              v = true;
              break;
            }
          }
          if (v == true) {
            break;
          }
        }
        return v;
      }

      window.onload=function() {
        var es = Element.descendants('body');
        for (var i = 0; i < es.length; i++ ) {
          if (!isVisible(es[i])) {
            alert(es[i].tagName);
          }
        }
      }
    </script>
  </head>
  <body id='body'>
    <div class="s"><p>This is text</p><p>More text</p></div>
    <div class="r">This is relative</div>
    <div class="of"><p>This is too wide...</p><pre>hidden</pre>
    <div class="iv">This is invisible</div>
    <div class="dn">This is display none</div>
  </body>
</html>
Mr. Shiny and New
A: 

Hi Macha, the answer is quite simple if you're still able to use prototype (prototypejs):

$('HtmlElementID').visible(); returns: true|false

Tristan

Tr1stan
This only checks for the first point. It doesn't affect the second or third at all.
Macha
A: 

I don't think checking the element's own visibility and display properties is good enough for requirement #1, even if you use currentStyle/getComputedStyle. You also have to check the element's ancestors. If an ancestor is hidden, so is the element.

jkl
+3  A: 

I don't know how much of this is supported in older or not-so-modern browsers, but I'm using something like this (without the neeed for any libraries):

function visible(element) {
  if (element.offsetWidth === 0 || element.offsetHeight === 0) return false;
  var height = document.documentElement.clientHeight,
      rects = element.getClientRects(),
      on_top = function(r) {
        var x = (r.left + r.right)/2, y = (r.top + r.bottom)/2;
        document.elementFromPoint(x, y) === element;
      };
  for (var i = 0, l = rects.length; i < l; i++) {
    var r = rects[i],
        in_viewport = r.top > 0 ? r.top <= height : (r.bottom > 0 && r.bottom <= height);
    if (in_viewport && on_top(r)) return true;
  }
  return false;
}

It checks that the element has an area > 0 and then it checks if any part of the element is within the viewport and that it is not hidden "under" another element (actually I only check on a single point in the center of the element, so it's not 100% assured -- but you could just modify the script to itterate over all the points of the element, if you really need to...).

Update

Modified on_top function that check every pixel:

on_top = function(r) {
  for (var x = Math.floor(r.left), x_max = Math.ceil(r.right); x <= x_max; x++)
  for (var y = Math.floor(r.top), y_max = Math.ceil(r.bottom); y <= y_max; y++) {
    if (document.elementFromPoint(x, y) === element) return true;
  }
  return false;
};

Don't know about the performance :)

Tobias
A: 

As jkl pointed out, checking the element's visibility or display is not enough. You do have to check its ancestors. Selenium does this when it verifies visibility on an element.

Check out the method Selenium.prototype.isVisible in the selenium-api.js file.

http://svn.openqa.org/svn/selenium-on-rails/selenium-on-rails/selenium-core/scripts/selenium-api.js

Jason Tillery