Skip to content

Instantly share code, notes, and snippets.

@drabiter
Created August 22, 2013 05:01
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 drabiter/6303383 to your computer and use it in GitHub Desktop.
Save drabiter/6303383 to your computer and use it in GitHub Desktop.
Reveal a section when reached viewport. Original source: http://jsfiddle.net/gbhVy/1/
<html>
<head>
<title>Test</title>
<link rel="stylesheet" src="style.css">
</head>
<body>
<div class="spacer">Spacer</div>
<div id="comments">
<div class="container">
Comments
</div>
</div>
<div>Footer</div>
<script src="plugin.js"></script>
</body>
</html>
/* ------------------------------ jQuery Plugin ------------------------------ */
;(function(window, document, $, undefined) {
/**
* Determines if an element was scrolled into view.
* @param {!Element} el
* @return {!Boolean}
**/
var wasScrolledIntoView = (function() {
var e;
(e = document.documentElement || document.body.parentNode) && typeof e.scrollTop == 'number' ? e : e = document.body;
return function wasScrolledIntoView(el) {
var rect = el.getBoundingClientRect();
return rect.top < e.clientHeight;
}
})();
// Global timer/listener
var scrollTimer;
var elements = [];
$(window).on('scroll', function() {
clearTimeout(scrollTimer);
scrollTimer = setTimeout(function() {
var i;
var l;
var wasInView;
for (i = 0, l = elements.length; i < l; i++) {
wasInView = wasScrolledIntoView(elements[i][0][0]);
if (elements[i][0].data('_wasScrolledIntoView') != wasInView) {
elements[i][0].data('_wasScrolledIntoView', wasInView);
elements[i][1].call(elements[i][0], wasInView);
}
}
}, 50);
});
// Pluginify
$.fn.wasScrolledIntoView = function(hollaback) {
this.each(function() {
elements.push([$(this), hollaback || $.noop]);
});
};
})(this, this.document, jQuery);
/* ------------------------------ Usage ------------------------------ */
$('#comments').wasScrolledIntoView(function(wasInView) {
$(this).toggleClass('show-comments', wasInView);
});
.spacer { background: lightgrey; height: 1000px; }
#comments .container { display: none; background: lightblue; padding: 20px 0; height: 250px; }
#comments.show-comments .container { display: block; }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment