Skip to content

Instantly share code, notes, and snippets.

@hssm
Last active February 14, 2016 02: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 hssm/1a8136059011e491d0d8 to your computer and use it in GitHub Desktop.
Save hssm/1a8136059011e491d0d8 to your computer and use it in GitHub Desktop.
Auto-scroll page to bottom when new content is added, but stop auto-scrolling if user scrolls up
<!DOCTYPE html5>
<html>
<head>
<meta charset="utf-8" />
<title>Latch to bottom unless scrolled up</title>
<script>
document.addEventListener("DOMNodeInserted", function () {
var b = document.body;
// Additional padding/border to account for in calculations
var offset = b.scrollHeight - b.offsetHeight;
// Amount we have scrolled down
var scrollPos = b.scrollTop + offset;
// Amount of scroll available, minus the visible portion (because scrollPos
// is the *top* of the visible portion)
var scrollBottom = (b.scrollHeight - (b.clientHeight + offset));
//console.log("offset: " + offset);
//console.log("scrollPos:" + scrollPos);
//console.log("scrollBottom:" + scrollBottom);
// If we are at the bottom, go to the bottom again.
if (scrollPos >= scrollBottom) {
window.scrollTo(0, document.body.scrollHeight);
}
}, false);
</script>
</head>
<body>
<!-- Some real content might go here -->
<script>
var n = 0;
setInterval(function() {
node = document.createElement("p");
node.innerHTML = "Line " + n;
document.body.appendChild(node);
n += 1;
}, 500);
</script>
</body>
</html>
@hssm
Copy link
Author

hssm commented Feb 2, 2016

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