From 444626696711622a9627782998d32e21304a972c Mon Sep 17 00:00:00 2001 From: Egor Date: Tue, 17 Feb 2015 18:17:06 +0200 Subject: [PATCH] Add additional param offset Param offset is needed when you are working with fixed elements. It fix the problems when you have some header which is fixed at the top of the page, and you are trying to check if some item is visible. When item is under the fixed header block, user doesn't see this item, but plugin returns true (item is visible), since it top offset is greater than 0. If you Pass param offset to visible function you'll check whether element is visible under offset. Param offset accepts simple number or object {top: 1, bottom: 2} etc. --- jquery.visible.js | 32 +++++++++++++++++++++++--------- 1 file changed, 23 insertions(+), 9 deletions(-) diff --git a/jquery.visible.js b/jquery.visible.js index 745956a..350f9de 100644 --- a/jquery.visible.js +++ b/jquery.visible.js @@ -11,7 +11,7 @@ * only accounts for vertical position, not horizontal. */ var $w = $(window); - $.fn.visible = function(partial,hidden,direction){ + $.fn.visible = function(partial,hidden,direction,offset){ if (this.length < 1) return; @@ -23,16 +23,30 @@ direction = (direction) ? direction : 'both', clientSize = hidden === true ? t.offsetWidth * t.offsetHeight : true; + var defaultOffset = 0; + // check if offset is a number + if (!isNaN(parseFloat(offset)) && isFinite(offset)) { + defaultOffset = offset; + offset = {}; + } + if (typeof offset !== 'object') offset = {}; + + offset = offset || {}; + offset.top = offset.top || defaultOffset; + offset.bottom = offset.bottom || defaultOffset; + offset.left = offset.left || defaultOffset; + offset.right = offset.right || defaultOffset; + if (typeof t.getBoundingClientRect === 'function'){ - // Use this native browser method, if available. - var rec = t.getBoundingClientRect(), - tViz = rec.top >= 0 && rec.top < vpHeight, - bViz = rec.bottom > 0 && rec.bottom <= vpHeight, - lViz = rec.left >= 0 && rec.left < vpWidth, - rViz = rec.right > 0 && rec.right <= vpWidth, - vVisible = partial ? tViz || bViz : tViz && bViz, - hVisible = partial ? lViz || rViz : lViz && rViz; + // Use this native browser method, if available. + var rec = t.getBoundingClientRect(), + tViz = rec.top >= offset.top && rec.top < vpHeight, + bViz = rec.bottom > offset.bottom && rec.bottom <= vpHeight, + lViz = rec.left >= offset.left && rec.left < vpWidth, + rViz = rec.right > offset.right && rec.right <= vpWidth, + vVisible = partial ? tViz || bViz : tViz && bViz, + hVisible = partial ? lViz || rViz : lViz && rViz; if(direction === 'both') return clientSize && vVisible && hVisible;