Skip to content

Instantly share code, notes, and snippets.

@hssm hssm/latch.html
Last active Feb 14, 2016

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

hssm commented Feb 2, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.