Skip to content

Instantly share code, notes, and snippets.

@albburtsev
Created February 3, 2011 12:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save albburtsev/809417 to your computer and use it in GitHub Desktop.
Save albburtsev/809417 to your computer and use it in GitHub Desktop.
Viewport Event jQuery Plugin
/*
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