Reputation: 1900
I'm trying to find a jquery plugin that help me determine if an object is in the viewport, but each one that I try reports all objects clearly in the viewport and below as being in the viewport. They all do this. The last one I tried, the verge plugin, has an option to show the viewport height using verge.viewportH()
. The value that this returns on my page is the height of the entire document. I think this might be the source of the problem. Has anyone seen this behaviour?
Here's a sample doc that show's the error in action:
Upvotes: 1
Views: 320
Reputation: 43870
window.innerHeight
will return the client browser's viewable area including the scrollbar if any. Don't use jQuery. If you want accurate dimensions, use JavaScript. There shouldn't be any compatibility problems using JS with jQ unless you are referencing, collecting, manipulating, etc. elements.
PLUNKER
var vpHeight = window.innerHeight;
var vpWidth = window.innerWidth;
document.getElementById('out').innerHTML = "Viewport Height: " + vpHeight + "px<br/><br/>Viewport Width: " + vpWidth + "px";
<h3>View this in Full Page Mode</h3>
<p>If viewed within a reduced window of Snippet's iframe, it will only return measurements of iframe since iframe's window is different than client's window object. Reload after resizing browser for accurate dimensions.</p>
<output id='out'></output><br/><br/>
<button onclick='location.reload()'>Reload</button>
Upvotes: 1
Reputation: 690
Here you go:
(function($) {
$.inviewport = function(element, settings) {
var __window = $(window),
__bottom = __window.height() + __window.scrollTop() + settings[2],
__top = __window.scrollTop() + settings[0],
__right = __window.width() + __window.scrollLeft() + settings[1],
__left = __window.scrollLeft() + settings[3],
__elem = $(element);
return
!(__bottom <= __elem.offset().top)
&& !(__top >= __elem.offset().top + __elem.height())
&& !(__right <= __elem.offset().left)
&& !(__left >= __elem.offset().left + __elem.width());
};
$.extend($.expr[':'], {
"in-viewport": function(a, i, m) {
return $.inviewport(a, m[3].split(',').map(function(x){ return x*1; }));
}
});
})(jQuery);
you can use it like this:
$(':in-viewport(100,0,1,0)');
where the parameters (top, right, bottom, left are the margins that you want to add to the original viewport, you can pass 0 if you want the exact viewport.
codepen: http://codepen.io/shotap/pen/meQLZP
Upvotes: 1