Last active
February 14, 2016 02:01
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Run it