Skip to content

Instantly share code, notes, and snippets.

@MayamaTakeshi
Created January 14, 2022 07:06
Show Gist options
  • Save MayamaTakeshi/68e44eb169dd961a48b84cd817939208 to your computer and use it in GitHub Desktop.
Save MayamaTakeshi/68e44eb169dd961a48b84cd817939208 to your computer and use it in GitHub Desktop.
Element insertion with conditional auto scroll
<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