Reputation: 68
I need to check if a dom-elment is visible in the viewport in different "visibility levels". I know how to check if it's visible or not, but this time i need an indicator of how visible the element is. Think of it as 3 colors: Green, Yellow and Red. Where green is 100% visible and red is not visible at all.
Does anyone have any ideas on how to write jQuery or Javascript for this?
Edit: 0 to 100 would also be a great indicator. 0 is 0 % visible and 100 is 100% visible.
Upvotes: 0
Views: 154
Reputation: 18292
Fortunately for you, I had to develop almost what you want. It's a jQuery extension that tells you how visible an element is relative to the browser window. It returns an object with two properties, horizontal and vertical. If vertical value is -1, then the element is invisible and over the viewport. If it is 0, then it's visible. If the result if 1, then invisible but under the viewport. Similarly for horizontal.
The difference is that '0' doesn't differentiate between 'completely in the viewport' or partially in the viewport. I needed it to determinate if something was above, in, or below the viewport (and the same for left and right). However, it's a good point to start and it can easily be changed to what you need.
jQuery.fn.viewportPosition = function () {
var $window = $(window);
var position = this.offset();
var viewport = { bottom: $window.height(), right: $window.width() };
var rect = { top: position.top, left: position.left, bottom: position.top + this.height(), right: position.left + this.width() };
return {
vertical: (rect.bottom < 0) ? -1 : (rect.top > viewport.bottom) ? 1 : 0,
horizontal: (rect.left < 0) ? -1 : (rect.left > viewport.right) ? 1 : 0
};
};
Upvotes: 1