Created
December 22, 2017 10:14
-
-
Save cirias/a05f569838a4d7c2ce1d2924a8969020 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
<div id="main"> | |
<div id="window"> | |
<div class="parent"></div> | |
</div> | |
</div> | |
<style> | |
div#main { | |
width: 100%; | |
} | |
div#window { | |
width: 100%; | |
overflow: auto; | |
} | |
.parent { | |
display: flex; | |
position: relative; | |
} | |
.child { | |
position: absolute; | |
background-color: cadetblue; | |
} | |
.cursor { | |
background-color: red; | |
width: 4px; | |
position: absolute; | |
height: 50px; | |
} | |
</style> | |
<script> | |
const height = 50; | |
const width = 10; | |
const count = 8000; | |
const bufferSize = 10; | |
const data = []; | |
for (let i = 0; i < count; i++) { | |
if (Math.floor(i/10)%2 === 0) { | |
data.push((i%10)/10); | |
} else { | |
data.push(1-(i%10)/10); | |
} | |
} | |
const parent = document.querySelector('.parent'); | |
parent.style.height = height; | |
parent.style.width = width * count; | |
const w = document.querySelector('#window'); | |
w.onscroll = update; | |
let prevFrom = 0; | |
let prevTo = 0; | |
function createChild(i) { | |
const child = document.createElement('div'); | |
child.className = "child" | |
child.style.height = data[i]*height; | |
child.style.width = width; | |
child.style.left = i*width; | |
return child; | |
} | |
function update() { | |
const from = Math.max(Math.floor(w.scrollLeft / width) - bufferSize, 0); | |
const to = Math.min(Math.ceil((w.scrollLeft + w.offsetWidth) / width) + bufferSize, count) + 1; | |
const shouldRemove = (_, i) => (i + prevFrom) < from || (i + prevFrom) >= to; | |
Array.prototype.filter.call(parent.children, shouldRemove).forEach(child => { | |
parent.removeChild(child); | |
}); | |
for (let i = Math.max(from, prevTo); i < to; i++) { | |
const child = createChild(i); | |
parent.appendChild(child); | |
} | |
for (let i = Math.min(to, prevFrom)-1; i >= from; i--) { | |
const child = createChild(i); | |
parent.insertBefore(child, parent.firstElementChild); | |
} | |
console.log(parent.children.length, from, to); | |
prevFrom = from; | |
prevTo = to; | |
} | |
window.onresize = update; | |
update(); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment