JSFiddle - React, Tailwind, and code Playground
HTML
<div class="container">
<div class="red"></div>
<div class="blue"></div>
<div class="yellow"></div>
<div class="green"></div>
</div>
CSS
body {
height: 200vh;
overflow-x: hidden;
}
.container {
display: flex;
flex-shrink: 0;
margin-top: 150vh;
position: absolute;
}
.red,
.blue {
height: 200px;
}
.red {
background-color: red;
min-width: 100px;
}
.blue {
background-color: blue;
min-width: 100px;
}
.yellow {
background-color: yellow;
min-width: 100px;
}
.green {
background-color: green;
min-width: 100px;
}
JavaScript
function isVisible(ele) {
const { top, bottom } = ele.getBoundingClientRect();
const vHeight = (window.innerHeight || document.documentElement.clientHeight);
return (
(top > 0 || bottom > 0) &&
top < vHeight
);
}
; (function () {
var throttle = function (type, name, obj) {
var obj = obj || window;
var running = false;
var func = function () {
if (running) { return; }
running = true;
requestAnimationFrame(function () {
obj.dispatchEvent(new CustomEvent(name));
running = false;
});
};
obj.addEventListener(type, func);
};
throttle("scroll", "optimizedScroll");
})();
window.addEventListener("optimizedScroll", function () {
var item = document.querySelector('.container');
if (isVisible(item)) {
window.addEventListener("optimizedScroll", function () {
item.style.transform = "translateX(-" + window.pageYOffset + "px)";
});
console.log("working");
}
});