JSFiddle - React, Tailwind, and code Playground
HTML
<div id='dad'></div>
CSS
#dad
{
overflow-y: scroll;
overflow-x: hidden;
width: 100px;
height: 600px;
}
JavaScript
var dad = $("#dad"),
tops = [],
bots = [],
oldScrollY;
for (var i = 0; i < 1000; i++) {
var iId = "child_" + i;
dad.append("<div id='" + iId + "'>" + i + "<br>ok ok<br>ya ya</div>");
var iChild = $("#" + iId);
iChild.css('backgroundColor', 'red');
var offs = iChild.offset();
tops.push(offs.top);
bots.push(offs.top + iChild.outerHeight());
}
var botsLen = bots.length,
dadHeight = dad.height(),
dadKids = dad.children(),
lastScrollY = 0,
ticking = false;
dad.bind('scroll', onScroll);
function onScroll() {
lastScrollY = dad.scrollTop();
requestTick();
}
function requestTick() {
if (!ticking) {
requestAnimationFrame(update);
ticking = true;
}
}
function update() {
var newScrollY = lastScrollY;
var isForward = newScrollY > oldScrollY;
var minVal = bSearch(bots, newScrollY, true);
var newScrollYHt = newScrollY + dadHeight;
var maxVal;
for (maxVal = minVal; maxVal < botsLen; maxVal++) {
var nxtTopSide = tops[maxVal];
if (nxtTopSide >= newScrollYHt) {
break;
}
}
maxVal = Math.min(maxVal, botsLen);
$(dadKids.slice(minVal, maxVal)).css('background', 'pink');
ticking = false;
}
/*
http://jsfromhell.com/array/search
*/
function bSearch(o, v, i) {
var h = o.length,
l = -1,
m;
while (h - l > 1)
if (o[m = h + l >> 1] < v) l = m;
else h = m;
return o[h] != v ? i ? h : -1 : h;
};
/*
http://paulirish.com/2011/requestanimationframe-for-smart-animating/
*/
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = (function() {
return window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
function( /* function FrameRequestCallback */ callback, /* DOMElement Element */ element) {
window.setTimeout(callback, 1000 / 60);
};
})();
}