JSFiddle - React, Tailwind, and code Playground
by velo_ninja
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
#redContainer {
position: relative;
width: 300px;
height: 900px;
overflow: auto;
border: 1px solid red;
}
.center-wrapper {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.blueBox {
width: 150px;
height: 150px;
background-color: blue;
margin: 5px;
transition: opacity 0.5s ease-out;
}
.blueBox.hidden {
opacity: 0;
}
</style>
<title>Scrollable Div with Blue Boxes</title>
</head>
<body>
<div id="redContainer">
<div class="center-wrapper">
<!-- Dynamically generated blue boxes will be placed here -->
</div>
</div>
<script>
function createBlueBox() {
const blueBox = document.createElement('div');
blueBox.className = 'blueBox';
return blueBox;
}
function addBlueBoxes() {
const centerWrapper = document.querySelector('.center-wrapper');
Array.from({ length: 10 }, createBlueBox).forEach(box => centerWrapper.appendChild(box));
}
function handleScroll() {
const redContainer = document.getElementById('redContainer');
const centerWrapper = document.querySelector('.center-wrapper');
const blueBoxes = centerWrapper.querySelectorAll('.blueBox');
const redRect = redContainer.getBoundingClientRect();
const offset = 50;
blueBoxes.forEach(box => {
const boxRect = box.getBoundingClientRect();
const overlap = Math.max(0, Math.min(boxRect.right, redRect.right) - Math.max(boxRect.left, redRect.left)) *
Math.max(0, Math.min(boxRect.bottom, redRect.bottom) - Math.max(boxRect.top, redRect.top));
const overlapPercentage = (overlap / (boxRect.width * boxRect.height)) * 100;
const shouldAppear = overlapPercentage < 100;
...