Created
April 16, 2013 10:46
-
-
Save stugoo/5394994 to your computer and use it in GitHub Desktop.
Detects if an element is in the viewport and then displays it
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
requires : | |
underscore js | |
event subscriber | |
*/ | |
inView = function (element) { | |
var self = this, | |
type, | |
overflow = 0, | |
initialise = function() { | |
type = element.getAttribute('data-view-type'); | |
SD.scroll.addSubscriber('scroll', _.throttle(function() { | |
var h = element.offsetHeight, | |
x = elementInViewport(element,h); | |
isInview(element,x); | |
}, 25)); | |
var h = element.offsetHeight, | |
x = elementInViewport(element,h); | |
isInview(element,x); | |
}, | |
isInview = function(el,visible){ | |
if( type == 'is-in-view') { | |
if(visible){ | |
el.style.visibility = ''; | |
} else { | |
el.style.visibility = 'hidden'; | |
} | |
} | |
}, | |
elementInViewport = function(el,h) { | |
var rect = el.getBoundingClientRect(), | |
view = false, | |
topInViewport = rect.top - window.innerHeight; | |
bottomInViewport = window.innerHeight - rect.bottom; | |
if(topInViewport < overflow ) { | |
view = true; | |
} | |
if( bottomInViewport > (window.innerHeight +overflow)){ | |
view = false; | |
} | |
return view; | |
}; | |
if(element) { | |
initialise(); | |
} | |
return this; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment