Skip to content

Instantly share code, notes, and snippets.

@hartzis
Created September 11, 2014 18:42
Show Gist options
  • Save hartzis/0034817feb4dda37147c to your computer and use it in GitHub Desktop.
Save hartzis/0034817feb4dda37147c to your computer and use it in GitHub Desktop.
window scroll event best practice
<!doctype html>
<html lang="en">
<head>
<title>JavaScript Patterns</title>
<meta charset="utf-8">
</head>
<body>
<script>
/* Title: window scroll event
* Description: avoid attaching handlers to the window scroll event
*/
// antipattern
$(window).scroll(function () {
$('.foo').something();
});
// preferred
var outerPane = $details.find(".details-pane-outer"),
didScroll = false;
$(window).scroll(function () {
didScroll = true;
});
setInterval(function () {
if (didScroll) {
didScroll = false;
// Check your page position and then
// Load in more results
// outerPane.html();
}
}, 250);
// preferred v2, timeout instead of interval - no unnecessary ticks
var scrollTimeout; // global for any pending scrollTimeout
var outerPane = $details.find(".details-pane-outer");
$(window).scroll(function () {
if (scrollTimeout) {
// clear the timeout, if one is pending
clearTimeout(scrollTimeout);
scrollTimeout = null;
}
scrollTimeout = setTimeout(scrollHandler, 250);
});
scrollHandler = function () {
// Check your page position and then
// Load in more results
// outerPane.html();
};
// References
// http://ejohn.org/blog/learning-from-twitter/
</script>
</body>
</html>
@chrispink
Copy link

$details ??

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment