Created
January 14, 2022 07:06
-
-
Save MayamaTakeshi/68e44eb169dd961a48b84cd817939208 to your computer and use it in GitHub Desktop.
Element insertion with conditional auto scroll
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
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> | |
<script> | |
window.onload = function() { | |
console.log('onload') | |
var parent = document.getElementById("parent") | |
var bottom = true | |
parent.addEventListener("scroll", function() { | |
if ((this.offsetHeight + this.scrollTop) >= this.scrollHeight) { | |
console.log('scroll to bottom') | |
bottom = true | |
} else { | |
console.log('scroll') | |
bottom = false | |
} | |
}) | |
setInterval(() => { | |
var node = document.createElement("LI"); | |
node.setAttribute("style", "display: none;"); | |
var textnode = document.createTextNode(new Date()); | |
node.appendChild(textnode); | |
var container = document.getElementById("container") | |
container.appendChild(node); | |
var length = $(container).children().length | |
if(length > 20) { | |
length = length - 20 | |
$(container).children().slice(0, length).remove() | |
} | |
$(node).fadeIn(1000, () => { | |
if(bottom) { | |
node.scrollIntoView({ behavior: 'smooth', block: 'center' }) | |
} | |
}) | |
}, 1000) | |
} | |
</script> | |
<body> | |
<div id="parent" style="background-color: lightblue; width: 600px; height: 120px; overflow: scroll;"> | |
<div id="container"/> | |
</div> | |
</body> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment