Skip to content

Instantly share code, notes, and snippets.

@boye
Created February 14, 2014 15:48
Show Gist options
  • Save boye/9003380 to your computer and use it in GitHub Desktop.
Save boye/9003380 to your computer and use it in GitHub Desktop.
Small plugin to implement a performant scroll listener (based on an idea by John Resig)
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<meta charset="utf-8">
<title>Perfscroll jQuery plugin</title>
</head>
<body>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<script>
$(function () {
// Small plugin to implement a performant scroll listener
// Based on an idea by John Resig
// @see: http://ejohn.org/blog/learning-from-twitter/
$.fn.perfscroll = function (fn, interval) {
var didScroll = false,
evt = null;
$(this).on('scroll', function (e) {
evt = e;
if ( !didScroll ) {
didScroll = true;
}
});
setInterval($.proxy(function () {
if ( didScroll ) {
didScroll = false;
if ( fn && $.isFunction(fn) ) {
fn.apply(this, [evt]);
}
}
}, this), interval || 250);
};
// Example
$(window).perfscroll(function (e) {
console.log(this.scrollTop());
// console.log(e); <-- onscroll event object
// console.log(this) <-- points to element
// ^ this means you can do someting like: if (this.scrollTop()>10) {}
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment