Created
February 3, 2011 12:32
-
-
Save albburtsev/809417 to your computer and use it in GitHub Desktop.
Viewport Event jQuery Plugin
This file contains 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
/* | |
Example: | |
$('div') | |
.viewport() | |
.one('viewport', function() { | |
$(this).addClass('view'); | |
}); | |
*/ | |
(function($) { | |
$.fn.viewport = function() { | |
var _this = $(this), _document = $(document), elem, | |
event = "viewport", | |
datakey = "vp", | |
vpTop, vpLeft, vpRight, vpBottom, | |
elTop, elLeft, elRight, elBottom, | |
detect = function() { | |
elem = $(this); | |
elTop = elem.offset().top; | |
elLeft = elem.offset().left; | |
elBottom = elTop + elem.height(); | |
elRight = elLeft + elem.width(); | |
var is = !( | |
elTop > vpBottom || | |
elBottom < vpTop || | |
elRight < vpLeft || | |
elLeft > vpRight | |
); | |
if ( is && elem.data(datakey) != is ) | |
elem.trigger(event); | |
elem.data(datakey. is); | |
}; | |
jQuery(window).bind('scroll resize', function() { | |
vpTop = _document.scrollTop(); | |
vpLeft = _document.scrollLeft(); | |
vpRight = vpLeft + (window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.offsetWidth); | |
vpBottom = vpTop + (window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.offsetHeight); | |
_this.each(detect); | |
}).trigger('scroll'); | |
return _this; | |
} | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment