<div class="tall">
<p>
An example of triggering an event when the user has scrolled to the bottom of the page.
</p>
<p>
As you scroll down you will notice a square that changes color and becomes a circle once you touch the bottom.
</p>
</div>
<div class="float" id="box">
</div>
html {
font-family: sans-serif;
}
p {
color: #0b3142;
text-align: center;
width: 80%;
margin: auto;
padding-top: 24px;
}
.tall {
height: 1000px;
}
.float {
width: 200px;
height: 200px;
position: absolute;
left: 50%;
top: 800px;
transform: translate(-50%, -50%);
background: #0f5257;
}
function scroller(fn) {
var debounceTimer = null;
function enableScroller() {
document.addEventListener("scroll", scrollLoad);
}
function disableScroller() {
document.removeEventListener("scroll", scrollLoad);
}
function testHeight() {
return _testHeight();
}
// have we scrolled to the end of the page?
function _testHeight() {
return (
window.pageYOffset + window.innerHeight >= document.body.scrollHeight
);
}
// Have scrolled far enough down the page?
function testScrollHeight() {
if (_testHeight()) {
disableScroller();
fn();
enableScroller();
}
}
function scrollLoad() {
clearTimeout(debounceTimer);
debounceTimer = setTimeout(testScrollHeight, 100);
}
return {
enableScroller,
disableScroller,
testHeight
};
}
function fireWhenScrolled() {
document.getElementById("box").style.background = "#C6B9CD";
document.getElementById("box").style["border-radius"] = "50%";
console.log("Bottom");
}
var activeScroller = scroller(fireWhenScrolled);
activeScroller.enableScroller();
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.